Skip to content

descriptors

BytesDescriptor

Bytes descriptor converts strings to bytes on write and converts bytes to str if represent_as_base64_str flag is set, so the value can be dumped to json

Source code in ormar/models/descriptors/descriptors.py
Python
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
class BytesDescriptor:
    """
    Bytes descriptor converts strings to bytes on write and converts bytes to str
    if represent_as_base64_str flag is set, so the value can be dumped to json
    """

    def __init__(self, name: str) -> None:
        self.name = name

    def __get__(self, instance: "Model", owner: type["Model"]) -> Any:
        value = instance.__dict__.get(self.name, None)
        field = instance.ormar_config.model_fields[self.name]
        if (
            value is not None
            and field.represent_as_base64_str
            and not isinstance(value, str)
        ):
            value = base64.b64encode(value).decode()
        return value

    def __set__(self, instance: "Model", value: Any) -> None:
        field = instance.ormar_config.model_fields[self.name]
        if isinstance(value, str):
            value = decode_bytes(
                value=value, represent_as_string=field.represent_as_base64_str
            )
        instance._internal_set(self.name, value)
        instance.set_save_status(False)

JsonDescriptor

Json descriptor dumps/loads strings to actual data on write/read

Source code in ormar/models/descriptors/descriptors.py
Python
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
class JsonDescriptor:
    """
    Json descriptor dumps/loads strings to actual data on write/read
    """

    def __init__(self, name: str) -> None:
        self.name = name

    def __get__(self, instance: "Model", owner: type["Model"]) -> Any:
        value = instance.__dict__.get(self.name, None)
        return value

    def __set__(self, instance: "Model", value: Any) -> None:
        value = encode_json(value)
        instance._internal_set(self.name, value)
        instance.set_save_status(False)

PkDescriptor

Descriptor of Model.pk, reading and writing the key value through the model's PrimaryKey.

Source code in ormar/models/descriptors/descriptors.py
Python
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
class PkDescriptor:
    """
    Descriptor of ``Model.pk``, reading and writing the key value through the
    model's ``PrimaryKey``.
    """

    def __init__(self, *, key: "PrimaryKey") -> None:
        """
        :param key: primary key of the model class
        :type key: PrimaryKey
        """
        self.key = key
        self.read = key.value

    def __get__(self, instance: "Model", owner: type["Model"]) -> Any:
        """
        :param instance: model instance
        :type instance: Model
        :param owner: model class
        :type owner: type[Model]
        :raises AttributeError: on class access, so the model metaclass resolves
            ``Model.pk`` to a key accessor for python-style filters
        :return: key value of the instance
        :rtype: Any
        """
        if instance is None:
            raise AttributeError("pk")
        return self.read(instance)

    def __set__(self, instance: "Model", value: Any) -> None:
        """
        Sets every key field of the instance and marks it as not saved.

        :param instance: model instance
        :type instance: Model
        :param value: new key value
        :type value: Any
        """
        instance.remember_persisted_key()
        for field_name, part in self.key.to_dict(value=value).items():
            if field_name in self.key.relation_parts:
                setattr(instance, field_name, part)
            else:
                instance._internal_set(name=field_name, value=part)
        instance.set_save_status(False)

__get__(instance, owner)

Parameters:

Name Type Description Default
instance Model

model instance

required
owner type[Model]

model class

required

Returns:

Type Description
Any

key value of the instance

Raises:

Type Description
AttributeError

on class access, so the model metaclass resolves Model.pk to a key accessor for python-style filters

Source code in ormar/models/descriptors/descriptors.py
Python
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
def __get__(self, instance: "Model", owner: type["Model"]) -> Any:
    """
    :param instance: model instance
    :type instance: Model
    :param owner: model class
    :type owner: type[Model]
    :raises AttributeError: on class access, so the model metaclass resolves
        ``Model.pk`` to a key accessor for python-style filters
    :return: key value of the instance
    :rtype: Any
    """
    if instance is None:
        raise AttributeError("pk")
    return self.read(instance)

__init__(*, key)

Parameters:

Name Type Description Default
key PrimaryKey

primary key of the model class

required
Source code in ormar/models/descriptors/descriptors.py
Python
85
86
87
88
89
90
91
def __init__(self, *, key: "PrimaryKey") -> None:
    """
    :param key: primary key of the model class
    :type key: PrimaryKey
    """
    self.key = key
    self.read = key.value

__set__(instance, value)

Sets every key field of the instance and marks it as not saved.

Parameters:

Name Type Description Default
instance Model

model instance

required
value Any

new key value

required
Source code in ormar/models/descriptors/descriptors.py
Python
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
def __set__(self, instance: "Model", value: Any) -> None:
    """
    Sets every key field of the instance and marks it as not saved.

    :param instance: model instance
    :type instance: Model
    :param value: new key value
    :type value: Any
    """
    instance.remember_persisted_key()
    for field_name, part in self.key.to_dict(value=value).items():
        if field_name in self.key.relation_parts:
            setattr(instance, field_name, part)
        else:
            instance._internal_set(name=field_name, value=part)
    instance.set_save_status(False)

PydanticDescriptor

Pydantic descriptor simply delegates everything to pydantic model

Source code in ormar/models/descriptors/descriptors.py
Python
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class PydanticDescriptor:
    """
    Pydantic descriptor simply delegates everything to pydantic model
    """

    def __init__(self, name: str) -> None:
        self.name = name

    def __get__(self, instance: "Model", owner: type["Model"]) -> Any:
        value = instance.__dict__.get(self.name, None)
        return value

    def __set__(self, instance: "Model", value: Any) -> None:
        instance._internal_set(self.name, value)
        instance.set_save_status(False)

RelationDescriptor

Relation descriptor expands the relation to initialize the related model before setting it to dict. Note that expanding also registers the related model in RelationManager.

Source code in ormar/models/descriptors/descriptors.py
Python
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
class RelationDescriptor:
    """
    Relation descriptor expands the relation to initialize the related model
    before setting it to __dict__. Note that expanding also registers the
    related model in RelationManager.
    """

    def __init__(self, name: str) -> None:
        self.name = name

    def __get__(self, instance: "Model", owner: type["Model"]) -> Any:
        if self.name in instance._orm:
            return instance._orm.get(self.name)  # type: ignore
        return None  # pragma no cover

    def __set__(self, instance: "Model", value: Any) -> None:
        field = instance.ormar_config.model_fields[self.name]
        unlink_previous_one_to_one(instance=instance, field=field, value=value)
        field.expand_relationship(value=value, child=instance)

        if (
            value is None
            and field.nullable
            and not field.virtual
            and not field.is_multi
            and self.name in instance._orm
        ):
            previous = cast(Optional["Model"], instance._orm.get(self.name))
            if previous is not None:
                instance._orm.remove(self.name, previous)

        if not isinstance(instance.__dict__.get(self.name), list):
            instance.set_save_status(False)