Skip to content

models

Definition of Model, it's parents NewBaseModel and mixins used by models. Also defines a Metaclass that handles all constructions and relations registration, ass well as vast number of helper functions for pydantic, sqlalchemy and relations.

ExcludableItems

Keeps a dictionary of Excludables by alias + model_name keys to allow quick lookup by nested models without need to travers deeply nested dictionaries and passing include/exclude around

Source code in ormar\models\excludable.py
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
class ExcludableItems:
    """
    Keeps a dictionary of Excludables by alias + model_name keys
    to allow quick lookup by nested models without need to travers
    deeply nested dictionaries and passing include/exclude around
    """

    def __init__(self) -> None:
        self.items: Dict[str, Excludable] = dict()

    @classmethod
    def from_excludable(cls, other: "ExcludableItems") -> "ExcludableItems":
        """
        Copy passed ExcludableItems to avoid inplace modifications.

        :param other: other excludable items to be copied
        :type other: ormar.models.excludable.ExcludableItems
        :return: copy of other
        :rtype: ormar.models.excludable.ExcludableItems
        """
        new_excludable = cls()
        for key, value in other.items.items():
            new_excludable.items[key] = value.get_copy()
        return new_excludable

    def include_entry_count(self) -> int:
        """
        Returns count of include items inside
        """
        count = 0
        for key in self.items.keys():
            count += len(self.items[key].include)
        return count

    def get(self, model_cls: Type["Model"], alias: str = "") -> Excludable:
        """
        Return Excludable for given model and alias.

        :param model_cls: target model to check
        :type model_cls: ormar.models.metaclass.ModelMetaclass
        :param alias: table alias from relation manager
        :type alias: str
        :return: Excludable for given model and alias
        :rtype: ormar.models.excludable.Excludable
        """
        key = f"{alias + '_' if alias else ''}{model_cls.get_name(lower=True)}"
        excludable = self.items.get(key)
        if not excludable:
            excludable = Excludable()
            self.items[key] = excludable
        return excludable

    def build(
        self,
        items: Union[List[str], str, Tuple[str], Set[str], Dict],
        model_cls: Type["Model"],
        is_exclude: bool = False,
    ) -> None:
        """
        Receives the one of the types of items and parses them as to achieve
        a end situation with one excludable per alias/model in relation.

        Each excludable has two sets of values - one to include, one to exclude.

        :param items: values to be included or excluded
        :type items: Union[List[str], str, Tuple[str], Set[str], Dict]
        :param model_cls: source model from which relations are constructed
        :type model_cls: ormar.models.metaclass.ModelMetaclass
        :param is_exclude: flag if items should be included or excluded
        :type is_exclude: bool
        """
        if isinstance(items, str):
            items = {items}

        if isinstance(items, Dict):
            self._traverse_dict(
                values=items,
                source_model=model_cls,
                model_cls=model_cls,
                is_exclude=is_exclude,
            )

        else:
            items = set(items)
            nested_items = set(x for x in items if "__" in x)
            items.difference_update(nested_items)
            self._set_excludes(
                items=items,
                model_name=model_cls.get_name(lower=True),
                is_exclude=is_exclude,
            )
            if nested_items:
                self._traverse_list(
                    values=nested_items, model_cls=model_cls, is_exclude=is_exclude
                )

    def _set_excludes(
        self, items: Set, model_name: str, is_exclude: bool, alias: str = ""
    ) -> None:
        """
        Sets set of values to be included or excluded for given key and model.

        :param items: items to include/exclude
        :type items: set
        :param model_name: name of model to construct key
        :type model_name: str
        :param is_exclude: flag if values should be included or excluded
        :type is_exclude: bool
        :param alias:
        :type alias: str
        """
        key = f"{alias + '_' if alias else ''}{model_name}"
        excludable = self.items.get(key)
        if not excludable:
            excludable = Excludable()
        excludable.set_values(value=items, is_exclude=is_exclude)
        self.items[key] = excludable

    def _traverse_dict(  # noqa: CFQ002
        self,
        values: Dict,
        source_model: Type["Model"],
        model_cls: Type["Model"],
        is_exclude: bool,
        related_items: List = None,
        alias: str = "",
    ) -> None:
        """
        Goes through dict of nested values and construct/update Excludables.

        :param values: items to include/exclude
        :type values: Dict
        :param source_model: source model from which relations are constructed
        :type source_model: ormar.models.metaclass.ModelMetaclass
        :param model_cls: model from which current relation is constructed
        :type model_cls: ormar.models.metaclass.ModelMetaclass
        :param is_exclude: flag if values should be included or excluded
        :type is_exclude: bool
        :param related_items: list of names of related fields chain
        :type related_items: List
        :param alias: alias of relation
        :type alias: str
        """
        self_fields = set()
        related_items = related_items[:] if related_items else []
        for key, value in values.items():
            if value is ...:
                self_fields.add(key)
            elif isinstance(value, set):
                (
                    table_prefix,
                    target_model,
                    _,
                    _,
                ) = get_relationship_alias_model_and_str(
                    source_model=source_model, related_parts=related_items + [key]
                )
                self._set_excludes(
                    items=value,
                    model_name=target_model.get_name(),
                    is_exclude=is_exclude,
                    alias=table_prefix,
                )
            else:
                # dict
                related_items.append(key)
                (
                    table_prefix,
                    target_model,
                    _,
                    _,
                ) = get_relationship_alias_model_and_str(
                    source_model=source_model, related_parts=related_items
                )
                self._traverse_dict(
                    values=value,
                    source_model=source_model,
                    model_cls=target_model,
                    is_exclude=is_exclude,
                    related_items=related_items,
                    alias=table_prefix,
                )
        if self_fields:
            self._set_excludes(
                items=self_fields,
                model_name=model_cls.get_name(),
                is_exclude=is_exclude,
                alias=alias,
            )

    def _traverse_list(
        self, values: Set[str], model_cls: Type["Model"], is_exclude: bool
    ) -> None:
        """
        Goes through list of values and construct/update Excludables.

        :param values: items to include/exclude
        :type values: set
        :param model_cls: model from which current relation is constructed
        :type model_cls: ormar.models.metaclass.ModelMetaclass
        :param is_exclude: flag if values should be included or excluded
        :type is_exclude: bool
        """
        # here we have only nested related keys
        for key in values:
            key_split = key.split("__")
            related_items, field_name = key_split[:-1], key_split[-1]
            (table_prefix, target_model, _, _) = get_relationship_alias_model_and_str(
                source_model=model_cls, related_parts=related_items
            )
            self._set_excludes(
                items={field_name},
                model_name=target_model.get_name(),
                is_exclude=is_exclude,
                alias=table_prefix,
            )

build(items, model_cls, is_exclude=False)

Receives the one of the types of items and parses them as to achieve a end situation with one excludable per alias/model in relation.

Each excludable has two sets of values - one to include, one to exclude.

Parameters:

Name Type Description Default
items Union[List[str], str, Tuple[str], Set[str], Dict]

values to be included or excluded

required
model_cls Type[Model]

source model from which relations are constructed

required
is_exclude bool

flag if items should be included or excluded

False
Source code in ormar\models\excludable.py
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
def build(
    self,
    items: Union[List[str], str, Tuple[str], Set[str], Dict],
    model_cls: Type["Model"],
    is_exclude: bool = False,
) -> None:
    """
    Receives the one of the types of items and parses them as to achieve
    a end situation with one excludable per alias/model in relation.

    Each excludable has two sets of values - one to include, one to exclude.

    :param items: values to be included or excluded
    :type items: Union[List[str], str, Tuple[str], Set[str], Dict]
    :param model_cls: source model from which relations are constructed
    :type model_cls: ormar.models.metaclass.ModelMetaclass
    :param is_exclude: flag if items should be included or excluded
    :type is_exclude: bool
    """
    if isinstance(items, str):
        items = {items}

    if isinstance(items, Dict):
        self._traverse_dict(
            values=items,
            source_model=model_cls,
            model_cls=model_cls,
            is_exclude=is_exclude,
        )

    else:
        items = set(items)
        nested_items = set(x for x in items if "__" in x)
        items.difference_update(nested_items)
        self._set_excludes(
            items=items,
            model_name=model_cls.get_name(lower=True),
            is_exclude=is_exclude,
        )
        if nested_items:
            self._traverse_list(
                values=nested_items, model_cls=model_cls, is_exclude=is_exclude
            )

from_excludable(other) classmethod

Copy passed ExcludableItems to avoid inplace modifications.

Parameters:

Name Type Description Default
other ExcludableItems

other excludable items to be copied

required

Returns:

Type Description
ormar.models.excludable.ExcludableItems

copy of other

Source code in ormar\models\excludable.py
75
76
77
78
79
80
81
82
83
84
85
86
87
88
@classmethod
def from_excludable(cls, other: "ExcludableItems") -> "ExcludableItems":
    """
    Copy passed ExcludableItems to avoid inplace modifications.

    :param other: other excludable items to be copied
    :type other: ormar.models.excludable.ExcludableItems
    :return: copy of other
    :rtype: ormar.models.excludable.ExcludableItems
    """
    new_excludable = cls()
    for key, value in other.items.items():
        new_excludable.items[key] = value.get_copy()
    return new_excludable

get(model_cls, alias='')

Return Excludable for given model and alias.

Parameters:

Name Type Description Default
model_cls Type[Model]

target model to check

required
alias str

table alias from relation manager

''

Returns:

Type Description
ormar.models.excludable.Excludable

Excludable for given model and alias

Source code in ormar\models\excludable.py
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
def get(self, model_cls: Type["Model"], alias: str = "") -> Excludable:
    """
    Return Excludable for given model and alias.

    :param model_cls: target model to check
    :type model_cls: ormar.models.metaclass.ModelMetaclass
    :param alias: table alias from relation manager
    :type alias: str
    :return: Excludable for given model and alias
    :rtype: ormar.models.excludable.Excludable
    """
    key = f"{alias + '_' if alias else ''}{model_cls.get_name(lower=True)}"
    excludable = self.items.get(key)
    if not excludable:
        excludable = Excludable()
        self.items[key] = excludable
    return excludable

include_entry_count()

Returns count of include items inside

Source code in ormar\models\excludable.py
90
91
92
93
94
95
96
97
def include_entry_count(self) -> int:
    """
    Returns count of include items inside
    """
    count = 0
    for key in self.items.keys():
        count += len(self.items[key].include)
    return count

Model

Bases: ModelRow

Source code in ormar\models\model.py
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 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
 77
 78
 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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
class Model(ModelRow):
    __abstract__ = False
    if TYPE_CHECKING:  # pragma nocover
        Meta: ModelMeta

    def __repr__(self) -> str:  # pragma nocover
        _repr = {
            k: getattr(self, k)
            for k, v in self.Meta.model_fields.items()
            if not v.skip_field
        }
        return f"{self.__class__.__name__}({str(_repr)})"

    async def upsert(self: T, **kwargs: Any) -> T:
        """
        Performs either a save or an update depending on the presence of the pk.
        If the pk field is filled it's an update, otherwise the save is performed.
        For save kwargs are ignored, used only in update if provided.

        :param kwargs: list of fields to update
        :type kwargs: Any
        :return: saved Model
        :rtype: Model
        """

        force_save = kwargs.pop("__force_save__", False)
        if force_save:
            expr = self.Meta.table.select().where(self.pk_column == self.pk)
            row = await self.Meta.database.fetch_one(expr)
            if not row:
                return await self.save()
            return await self.update(**kwargs)

        if not self.pk:
            return await self.save()
        return await self.update(**kwargs)

    async def save(self: T) -> T:
        """
        Performs a save of given Model instance.
        If primary key is already saved, db backend will throw integrity error.

        Related models are saved by pk number, reverse relation and many to many fields
        are not saved - use corresponding relations methods.

        If there are fields with server_default set and those fields
        are not already filled save will trigger also a second query
        to refreshed the fields populated server side.

        Does not recognize if model was previously saved.
        If you want to perform update or insert depending on the pk
        fields presence use upsert.

        Sends pre_save and post_save signals.

        Sets model save status to True.

        :return: saved Model
        :rtype: Model
        """
        await self.signals.pre_save.send(sender=self.__class__, instance=self)
        self_fields = self._extract_model_db_fields()

        if not self.pk and self.Meta.model_fields[self.Meta.pkname].autoincrement:
            self_fields.pop(self.Meta.pkname, None)
        self_fields = self.populate_default_values(self_fields)
        self.update_from_dict(
            {
                k: v
                for k, v in self_fields.items()
                if k not in self.extract_related_names()
            }
        )

        self_fields = self.translate_columns_to_aliases(self_fields)
        expr = self.Meta.table.insert()
        expr = expr.values(**self_fields)

        pk = await self.Meta.database.execute(expr)
        if pk and isinstance(pk, self.pk_type()):
            setattr(self, self.Meta.pkname, pk)

        self.set_save_status(True)
        # refresh server side defaults
        if any(
            field.server_default is not None
            for name, field in self.Meta.model_fields.items()
            if name not in self_fields
        ):
            await self.load()

        await self.signals.post_save.send(sender=self.__class__, instance=self)
        return self

    async def save_related(  # noqa: CCR001, CFQ002
        self,
        follow: bool = False,
        save_all: bool = False,
        relation_map: Dict = None,
        exclude: Union[Set, Dict] = None,
        update_count: int = 0,
        previous_model: "Model" = None,
        relation_field: Optional["ForeignKeyField"] = None,
    ) -> int:
        """
        Triggers a upsert method on all related models
        if the instances are not already saved.
        By default saves only the directly related ones.

        If follow=True is set it saves also related models of related models.

        To not get stuck in an infinite loop as related models also keep a relation
        to parent model visited models set is kept.

        That way already visited models that are nested are saved, but the save do not
        follow them inside. So Model A -> Model B -> Model A -> Model C will save second
        Model A but will never follow into Model C.
        Nested relations of those kind need to be persisted manually.

        :param relation_field: field with relation leading to this model
        :type relation_field: Optional[ForeignKeyField]
        :param previous_model: previous model from which method came
        :type previous_model: Model
        :param exclude: items to exclude during saving of relations
        :type exclude: Union[Set, Dict]
        :param relation_map: map of relations to follow
        :type relation_map: Dict
        :param save_all: flag if all models should be saved or only not saved ones
        :type save_all: bool
        :param follow: flag to trigger deep save -
        by default only directly related models are saved
        with follow=True also related models of related models are saved
        :type follow: bool
        :param update_count: internal parameter for recursive calls -
        number of updated instances
        :type update_count: int
        :return: number of updated/saved models
        :rtype: int
        """
        relation_map = (
            relation_map
            if relation_map is not None
            else translate_list_to_dict(self._iterate_related_models())
        )
        if exclude and isinstance(exclude, Set):
            exclude = translate_list_to_dict(exclude)
        relation_map = subtract_dict(relation_map, exclude or {})

        if relation_map:
            fields_to_visit = {
                field
                for field in self.extract_related_fields()
                if field.name in relation_map
            }
            pre_save = {
                field
                for field in fields_to_visit
                if not field.virtual and not field.is_multi
            }

            update_count = await self._update_relation_list(
                fields_list=pre_save,
                follow=follow,
                save_all=save_all,
                relation_map=relation_map,
                update_count=update_count,
            )

            update_count = await self._upsert_model(
                instance=self,
                save_all=save_all,
                previous_model=previous_model,
                relation_field=relation_field,
                update_count=update_count,
            )

            post_save = fields_to_visit - pre_save

            update_count = await self._update_relation_list(
                fields_list=post_save,
                follow=follow,
                save_all=save_all,
                relation_map=relation_map,
                update_count=update_count,
            )

        else:
            update_count = await self._upsert_model(
                instance=self,
                save_all=save_all,
                previous_model=previous_model,
                relation_field=relation_field,
                update_count=update_count,
            )

        return update_count

    async def update(self: T, _columns: List[str] = None, **kwargs: Any) -> T:
        """
        Performs update of Model instance in the database.
        Fields can be updated before or you can pass them as kwargs.

        Sends pre_update and post_update signals.

        Sets model save status to True.

        :param _columns: list of columns to update, if None all are updated
        :type _columns: List
        :raises ModelPersistenceError: If the pk column is not set

        :param kwargs: list of fields to update as field=value pairs
        :type kwargs: Any
        :return: updated Model
        :rtype: Model
        """
        if kwargs:
            self.update_from_dict(kwargs)

        if not self.pk:
            raise ModelPersistenceError(
                "You cannot update not saved model! Use save or upsert method."
            )

        await self.signals.pre_update.send(
            sender=self.__class__, instance=self, passed_args=kwargs
        )
        self_fields = self._extract_model_db_fields()
        self_fields.pop(self.get_column_name_from_alias(self.Meta.pkname))
        if _columns:
            self_fields = {k: v for k, v in self_fields.items() if k in _columns}
        self_fields = self.translate_columns_to_aliases(self_fields)
        expr = self.Meta.table.update().values(**self_fields)
        expr = expr.where(self.pk_column == getattr(self, self.Meta.pkname))

        await self.Meta.database.execute(expr)
        self.set_save_status(True)
        await self.signals.post_update.send(sender=self.__class__, instance=self)
        return self

    async def delete(self) -> int:
        """
        Removes the Model instance from the database.

        Sends pre_delete and post_delete signals.

        Sets model save status to False.

        Note it does not delete the Model itself (python object).
        So you can delete and later save (since pk is deleted no conflict will arise)
        or update and the Model will be saved in database again.

        :return: number of deleted rows (for some backends)
        :rtype: int
        """
        await self.signals.pre_delete.send(sender=self.__class__, instance=self)
        expr = self.Meta.table.delete()
        expr = expr.where(self.pk_column == (getattr(self, self.Meta.pkname)))
        result = await self.Meta.database.execute(expr)
        self.set_save_status(False)
        await self.signals.post_delete.send(sender=self.__class__, instance=self)
        return result

    async def load(self: T) -> T:
        """
        Allow to refresh existing Models fields from database.
        Be careful as the related models can be overwritten by pk_only models in load.
        Does NOT refresh the related models fields if they were loaded before.

        :raises NoMatch: If given pk is not found in database.

        :return: reloaded Model
        :rtype: Model
        """
        expr = self.Meta.table.select().where(self.pk_column == self.pk)
        row = await self.Meta.database.fetch_one(expr)
        if not row:  # pragma nocover
            raise NoMatch("Instance was deleted from database and cannot be refreshed")
        kwargs = dict(row)
        kwargs = self.translate_aliases_to_columns(kwargs)
        self.update_from_dict(kwargs)
        self.set_save_status(True)
        return self

    async def load_all(
        self: T,
        follow: bool = False,
        exclude: Union[List, str, Set, Dict] = None,
        order_by: Union[List, str] = None,
    ) -> T:
        """
        Allow to refresh existing Models fields from database.
        Performs refresh of the related models fields.

        By default, loads only self and the directly related ones.

        If follow=True is set it loads also related models of related models.

        To not get stuck in an infinite loop as related models also keep a relation
        to parent model visited models set is kept.

        That way already visited models that are nested are loaded, but the load do not
        follow them inside. So Model A -> Model B -> Model C -> Model A -> Model X
        will load second Model A but will never follow into Model X.
        Nested relations of those kind need to be loaded manually.

        :param order_by: columns by which models should be sorted
        :type order_by: Union[List, str]
        :raises NoMatch: If given pk is not found in database.

        :param exclude: related models to exclude
        :type exclude: Union[List, str, Set, Dict]
        :param follow: flag to trigger deep save -
        by default only directly related models are saved
        with follow=True also related models of related models are saved
        :type follow: bool
        :return: reloaded Model
        :rtype: Model
        """
        relations = list(self.extract_related_names())
        if follow:
            relations = self._iterate_related_models()
        queryset = self.__class__.objects
        if exclude:
            queryset = queryset.exclude_fields(exclude)
        if order_by:
            queryset = queryset.order_by(order_by)
        instance = await queryset.select_related(relations).get(pk=self.pk)
        self._orm.clear()
        self.update_from_dict(instance.dict())
        return self

delete() async

Removes the Model instance from the database.

Sends pre_delete and post_delete signals.

Sets model save status to False.

Note it does not delete the Model itself (python object). So you can delete and later save (since pk is deleted no conflict will arise) or update and the Model will be saved in database again.

Returns:

Type Description
int

number of deleted rows (for some backends)

Source code in ormar\models\model.py
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
async def delete(self) -> int:
    """
    Removes the Model instance from the database.

    Sends pre_delete and post_delete signals.

    Sets model save status to False.

    Note it does not delete the Model itself (python object).
    So you can delete and later save (since pk is deleted no conflict will arise)
    or update and the Model will be saved in database again.

    :return: number of deleted rows (for some backends)
    :rtype: int
    """
    await self.signals.pre_delete.send(sender=self.__class__, instance=self)
    expr = self.Meta.table.delete()
    expr = expr.where(self.pk_column == (getattr(self, self.Meta.pkname)))
    result = await self.Meta.database.execute(expr)
    self.set_save_status(False)
    await self.signals.post_delete.send(sender=self.__class__, instance=self)
    return result

load() async

Allow to refresh existing Models fields from database. Be careful as the related models can be overwritten by pk_only models in load. Does NOT refresh the related models fields if they were loaded before.

Returns:

Type Description
Model

reloaded Model

Raises:

Type Description
NoMatch

If given pk is not found in database.

Source code in ormar\models\model.py
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
async def load(self: T) -> T:
    """
    Allow to refresh existing Models fields from database.
    Be careful as the related models can be overwritten by pk_only models in load.
    Does NOT refresh the related models fields if they were loaded before.

    :raises NoMatch: If given pk is not found in database.

    :return: reloaded Model
    :rtype: Model
    """
    expr = self.Meta.table.select().where(self.pk_column == self.pk)
    row = await self.Meta.database.fetch_one(expr)
    if not row:  # pragma nocover
        raise NoMatch("Instance was deleted from database and cannot be refreshed")
    kwargs = dict(row)
    kwargs = self.translate_aliases_to_columns(kwargs)
    self.update_from_dict(kwargs)
    self.set_save_status(True)
    return self

load_all(follow=False, exclude=None, order_by=None) async

Allow to refresh existing Models fields from database. Performs refresh of the related models fields.

By default, loads only self and the directly related ones.

If follow=True is set it loads also related models of related models.

To not get stuck in an infinite loop as related models also keep a relation to parent model visited models set is kept.

That way already visited models that are nested are loaded, but the load do not follow them inside. So Model A -> Model B -> Model C -> Model A -> Model X will load second Model A but will never follow into Model X. Nested relations of those kind need to be loaded manually.

Parameters:

Name Type Description Default
order_by Union[List, str]

columns by which models should be sorted

None
exclude Union[List, str, Set, Dict]

related models to exclude

None
follow bool

flag to trigger deep save - by default only directly related models are saved with follow=True also related models of related models are saved

False

Returns:

Type Description
Model

reloaded Model

Raises:

Type Description
NoMatch

If given pk is not found in database.

Source code in ormar\models\model.py
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
async def load_all(
    self: T,
    follow: bool = False,
    exclude: Union[List, str, Set, Dict] = None,
    order_by: Union[List, str] = None,
) -> T:
    """
    Allow to refresh existing Models fields from database.
    Performs refresh of the related models fields.

    By default, loads only self and the directly related ones.

    If follow=True is set it loads also related models of related models.

    To not get stuck in an infinite loop as related models also keep a relation
    to parent model visited models set is kept.

    That way already visited models that are nested are loaded, but the load do not
    follow them inside. So Model A -> Model B -> Model C -> Model A -> Model X
    will load second Model A but will never follow into Model X.
    Nested relations of those kind need to be loaded manually.

    :param order_by: columns by which models should be sorted
    :type order_by: Union[List, str]
    :raises NoMatch: If given pk is not found in database.

    :param exclude: related models to exclude
    :type exclude: Union[List, str, Set, Dict]
    :param follow: flag to trigger deep save -
    by default only directly related models are saved
    with follow=True also related models of related models are saved
    :type follow: bool
    :return: reloaded Model
    :rtype: Model
    """
    relations = list(self.extract_related_names())
    if follow:
        relations = self._iterate_related_models()
    queryset = self.__class__.objects
    if exclude:
        queryset = queryset.exclude_fields(exclude)
    if order_by:
        queryset = queryset.order_by(order_by)
    instance = await queryset.select_related(relations).get(pk=self.pk)
    self._orm.clear()
    self.update_from_dict(instance.dict())
    return self

save() async

Performs a save of given Model instance. If primary key is already saved, db backend will throw integrity error.

Related models are saved by pk number, reverse relation and many to many fields are not saved - use corresponding relations methods.

If there are fields with server_default set and those fields are not already filled save will trigger also a second query to refreshed the fields populated server side.

Does not recognize if model was previously saved. If you want to perform update or insert depending on the pk fields presence use upsert.

Sends pre_save and post_save signals.

Sets model save status to True.

Returns:

Type Description
Model

saved Model

Source code in ormar\models\model.py
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 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
async def save(self: T) -> T:
    """
    Performs a save of given Model instance.
    If primary key is already saved, db backend will throw integrity error.

    Related models are saved by pk number, reverse relation and many to many fields
    are not saved - use corresponding relations methods.

    If there are fields with server_default set and those fields
    are not already filled save will trigger also a second query
    to refreshed the fields populated server side.

    Does not recognize if model was previously saved.
    If you want to perform update or insert depending on the pk
    fields presence use upsert.

    Sends pre_save and post_save signals.

    Sets model save status to True.

    :return: saved Model
    :rtype: Model
    """
    await self.signals.pre_save.send(sender=self.__class__, instance=self)
    self_fields = self._extract_model_db_fields()

    if not self.pk and self.Meta.model_fields[self.Meta.pkname].autoincrement:
        self_fields.pop(self.Meta.pkname, None)
    self_fields = self.populate_default_values(self_fields)
    self.update_from_dict(
        {
            k: v
            for k, v in self_fields.items()
            if k not in self.extract_related_names()
        }
    )

    self_fields = self.translate_columns_to_aliases(self_fields)
    expr = self.Meta.table.insert()
    expr = expr.values(**self_fields)

    pk = await self.Meta.database.execute(expr)
    if pk and isinstance(pk, self.pk_type()):
        setattr(self, self.Meta.pkname, pk)

    self.set_save_status(True)
    # refresh server side defaults
    if any(
        field.server_default is not None
        for name, field in self.Meta.model_fields.items()
        if name not in self_fields
    ):
        await self.load()

    await self.signals.post_save.send(sender=self.__class__, instance=self)
    return self

Triggers a upsert method on all related models if the instances are not already saved. By default saves only the directly related ones.

If follow=True is set it saves also related models of related models.

To not get stuck in an infinite loop as related models also keep a relation to parent model visited models set is kept.

That way already visited models that are nested are saved, but the save do not follow them inside. So Model A -> Model B -> Model A -> Model C will save second Model A but will never follow into Model C. Nested relations of those kind need to be persisted manually.

Parameters:

Name Type Description Default
relation_field Optional[ForeignKeyField]

field with relation leading to this model

None
previous_model Model

previous model from which method came

None
exclude Union[Set, Dict]

items to exclude during saving of relations

None
relation_map Dict

map of relations to follow

None
save_all bool

flag if all models should be saved or only not saved ones

False
follow bool

flag to trigger deep save - by default only directly related models are saved with follow=True also related models of related models are saved

False
update_count int

internal parameter for recursive calls - number of updated instances

0

Returns:

Type Description
int

number of updated/saved models

Source code in ormar\models\model.py
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
async def save_related(  # noqa: CCR001, CFQ002
    self,
    follow: bool = False,
    save_all: bool = False,
    relation_map: Dict = None,
    exclude: Union[Set, Dict] = None,
    update_count: int = 0,
    previous_model: "Model" = None,
    relation_field: Optional["ForeignKeyField"] = None,
) -> int:
    """
    Triggers a upsert method on all related models
    if the instances are not already saved.
    By default saves only the directly related ones.

    If follow=True is set it saves also related models of related models.

    To not get stuck in an infinite loop as related models also keep a relation
    to parent model visited models set is kept.

    That way already visited models that are nested are saved, but the save do not
    follow them inside. So Model A -> Model B -> Model A -> Model C will save second
    Model A but will never follow into Model C.
    Nested relations of those kind need to be persisted manually.

    :param relation_field: field with relation leading to this model
    :type relation_field: Optional[ForeignKeyField]
    :param previous_model: previous model from which method came
    :type previous_model: Model
    :param exclude: items to exclude during saving of relations
    :type exclude: Union[Set, Dict]
    :param relation_map: map of relations to follow
    :type relation_map: Dict
    :param save_all: flag if all models should be saved or only not saved ones
    :type save_all: bool
    :param follow: flag to trigger deep save -
    by default only directly related models are saved
    with follow=True also related models of related models are saved
    :type follow: bool
    :param update_count: internal parameter for recursive calls -
    number of updated instances
    :type update_count: int
    :return: number of updated/saved models
    :rtype: int
    """
    relation_map = (
        relation_map
        if relation_map is not None
        else translate_list_to_dict(self._iterate_related_models())
    )
    if exclude and isinstance(exclude, Set):
        exclude = translate_list_to_dict(exclude)
    relation_map = subtract_dict(relation_map, exclude or {})

    if relation_map:
        fields_to_visit = {
            field
            for field in self.extract_related_fields()
            if field.name in relation_map
        }
        pre_save = {
            field
            for field in fields_to_visit
            if not field.virtual and not field.is_multi
        }

        update_count = await self._update_relation_list(
            fields_list=pre_save,
            follow=follow,
            save_all=save_all,
            relation_map=relation_map,
            update_count=update_count,
        )

        update_count = await self._upsert_model(
            instance=self,
            save_all=save_all,
            previous_model=previous_model,
            relation_field=relation_field,
            update_count=update_count,
        )

        post_save = fields_to_visit - pre_save

        update_count = await self._update_relation_list(
            fields_list=post_save,
            follow=follow,
            save_all=save_all,
            relation_map=relation_map,
            update_count=update_count,
        )

    else:
        update_count = await self._upsert_model(
            instance=self,
            save_all=save_all,
            previous_model=previous_model,
            relation_field=relation_field,
            update_count=update_count,
        )

    return update_count

update(_columns=None, **kwargs) async

Performs update of Model instance in the database. Fields can be updated before or you can pass them as kwargs.

Sends pre_update and post_update signals.

Sets model save status to True.

Parameters:

Name Type Description Default
_columns List[str]

list of columns to update, if None all are updated

None
kwargs Any

list of fields to update as field=value pairs

{}

Returns:

Type Description
Model

updated Model

Raises:

Type Description
ModelPersistenceError

If the pk column is not set

Source code in ormar\models\model.py
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
async def update(self: T, _columns: List[str] = None, **kwargs: Any) -> T:
    """
    Performs update of Model instance in the database.
    Fields can be updated before or you can pass them as kwargs.

    Sends pre_update and post_update signals.

    Sets model save status to True.

    :param _columns: list of columns to update, if None all are updated
    :type _columns: List
    :raises ModelPersistenceError: If the pk column is not set

    :param kwargs: list of fields to update as field=value pairs
    :type kwargs: Any
    :return: updated Model
    :rtype: Model
    """
    if kwargs:
        self.update_from_dict(kwargs)

    if not self.pk:
        raise ModelPersistenceError(
            "You cannot update not saved model! Use save or upsert method."
        )

    await self.signals.pre_update.send(
        sender=self.__class__, instance=self, passed_args=kwargs
    )
    self_fields = self._extract_model_db_fields()
    self_fields.pop(self.get_column_name_from_alias(self.Meta.pkname))
    if _columns:
        self_fields = {k: v for k, v in self_fields.items() if k in _columns}
    self_fields = self.translate_columns_to_aliases(self_fields)
    expr = self.Meta.table.update().values(**self_fields)
    expr = expr.where(self.pk_column == getattr(self, self.Meta.pkname))

    await self.Meta.database.execute(expr)
    self.set_save_status(True)
    await self.signals.post_update.send(sender=self.__class__, instance=self)
    return self

upsert(**kwargs) async

Performs either a save or an update depending on the presence of the pk. If the pk field is filled it's an update, otherwise the save is performed. For save kwargs are ignored, used only in update if provided.

Parameters:

Name Type Description Default
kwargs Any

list of fields to update

{}

Returns:

Type Description
Model

saved Model

Source code in ormar\models\model.py
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
async def upsert(self: T, **kwargs: Any) -> T:
    """
    Performs either a save or an update depending on the presence of the pk.
    If the pk field is filled it's an update, otherwise the save is performed.
    For save kwargs are ignored, used only in update if provided.

    :param kwargs: list of fields to update
    :type kwargs: Any
    :return: saved Model
    :rtype: Model
    """

    force_save = kwargs.pop("__force_save__", False)
    if force_save:
        expr = self.Meta.table.select().where(self.pk_column == self.pk)
        row = await self.Meta.database.fetch_one(expr)
        if not row:
            return await self.save()
        return await self.update(**kwargs)

    if not self.pk:
        return await self.save()
    return await self.update(**kwargs)

ModelRow

Bases: NewBaseModel

Source code in ormar\models\model_row.py
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 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
 77
 78
 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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
class ModelRow(NewBaseModel):
    @classmethod
    def from_row(  # noqa: CFQ002
        cls,
        row: ResultProxy,
        source_model: Type["Model"],
        select_related: List = None,
        related_models: Any = None,
        related_field: "ForeignKeyField" = None,
        excludable: ExcludableItems = None,
        current_relation_str: str = "",
        proxy_source_model: Optional[Type["Model"]] = None,
        used_prefixes: List[str] = None,
    ) -> Optional["Model"]:
        """
        Model method to convert raw sql row from database into ormar.Model instance.
        Traverses nested models if they were specified in select_related for query.

        Called recurrently and returns model instance if it's present in the row.
        Note that it's processing one row at a time, so if there are duplicates of
        parent row that needs to be joined/combined
        (like parent row in sql join with 2+ child rows)
        instances populated in this method are later combined in the QuerySet.
        Other method working directly on raw database results is in prefetch_query,
        where rows are populated in a different way as they do not have
        nested models in result.

        :param used_prefixes: list of already extracted prefixes
        :type used_prefixes: List[str]
        :param proxy_source_model: source model from which querysetproxy is constructed
        :type proxy_source_model: Optional[Type["ModelRow"]]
        :param excludable: structure of fields to include and exclude
        :type excludable: ExcludableItems
        :param current_relation_str: name of the relation field
        :type current_relation_str: str
        :param source_model: model on which relation was defined
        :type source_model: Type[Model]
        :param row: raw result row from the database
        :type row: ResultProxy
        :param select_related: list of names of related models fetched from database
        :type select_related: List
        :param related_models: list or dict of related models
        :type related_models: Union[List, Dict]
        :param related_field: field with relation declaration
        :type related_field: ForeignKeyField
        :return: returns model if model is populated from database
        :rtype: Optional[Model]
        """
        item: Dict[str, Any] = {}
        select_related = select_related or []
        related_models = related_models or []
        table_prefix = ""
        used_prefixes = used_prefixes if used_prefixes is not None else []
        excludable = excludable or ExcludableItems()

        if select_related:
            related_models = group_related_list(select_related)

        if related_field:
            table_prefix = cls._process_table_prefix(
                source_model=source_model,
                current_relation_str=current_relation_str,
                related_field=related_field,
                used_prefixes=used_prefixes,
            )

        item = cls._populate_nested_models_from_row(
            item=item,
            row=row,
            related_models=related_models,
            excludable=excludable,
            current_relation_str=current_relation_str,
            source_model=source_model,  # type: ignore
            proxy_source_model=proxy_source_model,  # type: ignore
            table_prefix=table_prefix,
            used_prefixes=used_prefixes,
        )
        item = cls.extract_prefixed_table_columns(
            item=item, row=row, table_prefix=table_prefix, excludable=excludable
        )

        instance: Optional["Model"] = None
        if item.get(cls.Meta.pkname, None) is not None:
            item["__excluded__"] = cls.get_names_to_exclude(
                excludable=excludable, alias=table_prefix
            )
            instance = cast("Model", cls(**item))
            instance.set_save_status(True)
        return instance

    @classmethod
    def _process_table_prefix(
        cls,
        source_model: Type["Model"],
        current_relation_str: str,
        related_field: "ForeignKeyField",
        used_prefixes: List[str],
    ) -> str:
        """

        :param source_model: model on which relation was defined
        :type source_model: Type[Model]
        :param current_relation_str: current relation string
        :type current_relation_str: str
        :param related_field: field with relation declaration
        :type related_field: "ForeignKeyField"
        :param used_prefixes: list of already extracted prefixes
        :type used_prefixes: List[str]
        :return: table_prefix to use
        :rtype: str
        """
        if related_field.is_multi:
            previous_model = related_field.through
        else:
            previous_model = related_field.owner
        table_prefix = cls.Meta.alias_manager.resolve_relation_alias(
            from_model=previous_model, relation_name=related_field.name
        )
        if not table_prefix or table_prefix in used_prefixes:
            manager = cls.Meta.alias_manager
            table_prefix = manager.resolve_relation_alias_after_complex(
                source_model=source_model,
                relation_str=current_relation_str,
                relation_field=related_field,
            )
        used_prefixes.append(table_prefix)
        return table_prefix

    @classmethod
    def _populate_nested_models_from_row(  # noqa: CFQ002
        cls,
        item: dict,
        row: ResultProxy,
        source_model: Type["Model"],
        related_models: Any,
        excludable: ExcludableItems,
        table_prefix: str,
        used_prefixes: List[str],
        current_relation_str: str = None,
        proxy_source_model: Type["Model"] = None,
    ) -> dict:
        """
        Traverses structure of related models and populates the nested models
        from the database row.
        Related models can be a list if only directly related models are to be
        populated, converted to dict if related models also have their own related
        models to be populated.

        Recurrently calls from_row method on nested instances and create nested
        instances. In the end those instances are added to the final model dictionary.

        :param proxy_source_model: source model from which querysetproxy is constructed
        :type proxy_source_model: Optional[Type["ModelRow"]]
        :param excludable: structure of fields to include and exclude
        :type excludable: ExcludableItems
        :param source_model: source model from which relation started
        :type source_model: Type[Model]
        :param current_relation_str: joined related parts into one string
        :type current_relation_str: str
        :param item: dictionary of already populated nested models, otherwise empty dict
        :type item: Dict
        :param row: raw result row from the database
        :type row: ResultProxy
        :param related_models: list or dict of related models
        :type related_models: Union[Dict, List]
        :return: dictionary with keys corresponding to model fields names
        and values are database values
        :rtype: Dict
        """

        for related in related_models:
            field = cls.Meta.model_fields[related]
            field = cast("ForeignKeyField", field)
            model_cls = field.to
            model_excludable = excludable.get(
                model_cls=cast(Type["Model"], cls), alias=table_prefix
            )
            if model_excludable.is_excluded(related):
                continue

            relation_str, remainder = cls._process_remainder_and_relation_string(
                related_models=related_models,
                current_relation_str=current_relation_str,
                related=related,
            )
            child = model_cls.from_row(
                row,
                related_models=remainder,
                related_field=field,
                excludable=excludable,
                current_relation_str=relation_str,
                source_model=source_model,
                proxy_source_model=proxy_source_model,
                used_prefixes=used_prefixes,
            )
            item[model_cls.get_column_name_from_alias(related)] = child
            if (
                field.is_multi
                and child
                and not model_excludable.is_excluded(field.through.get_name())
            ):
                cls._populate_through_instance(
                    row=row,
                    item=item,
                    related=related,
                    excludable=excludable,
                    child=child,
                    proxy_source_model=proxy_source_model,
                )

        return item

    @staticmethod
    def _process_remainder_and_relation_string(
        related_models: Union[Dict, List],
        current_relation_str: Optional[str],
        related: str,
    ) -> Tuple[str, Optional[Union[Dict, List]]]:
        """
        Process remainder models and relation string

        :param related_models: list or dict of related models
        :type related_models: Union[Dict, List]
        :param current_relation_str: current relation string
        :type current_relation_str: Optional[str]
        :param related: name of the relation
        :type related: str
        """
        relation_str = (
            "__".join([current_relation_str, related])
            if current_relation_str
            else related
        )

        remainder = None
        if isinstance(related_models, dict) and related_models[related]:
            remainder = related_models[related]
        return relation_str, remainder

    @classmethod
    def _populate_through_instance(  # noqa: CFQ002
        cls,
        row: ResultProxy,
        item: Dict,
        related: str,
        excludable: ExcludableItems,
        child: "Model",
        proxy_source_model: Optional[Type["Model"]],
    ) -> None:
        """
        Populates the through model on reverse side of current query.
        Normally it's child class, unless the query is from queryset.

        :param row: row from db result
        :type row: ResultProxy
        :param item: parent item dict
        :type item: Dict
        :param related: current relation name
        :type related: str
        :param excludable: structure of fields to include and exclude
        :type excludable: ExcludableItems
        :param child: child item of parent
        :type child: "Model"
        :param proxy_source_model: source model from which querysetproxy is constructed
        :type proxy_source_model: Type["Model"]
        """
        through_name = cls.Meta.model_fields[related].through.get_name()
        through_child = cls._create_through_instance(
            row=row, related=related, through_name=through_name, excludable=excludable
        )

        if child.__class__ != proxy_source_model:
            setattr(child, through_name, through_child)
        else:
            item[through_name] = through_child
        child.set_save_status(True)

    @classmethod
    def _create_through_instance(
        cls,
        row: ResultProxy,
        through_name: str,
        related: str,
        excludable: ExcludableItems,
    ) -> "ModelRow":
        """
        Initialize the through model from db row.
        Excluded all relation fields and other exclude/include set in excludable.

        :param row: loaded row from database
        :type row: sqlalchemy.engine.ResultProxy
        :param through_name: name of the through field
        :type through_name: str
        :param related: name of the relation
        :type related: str
        :param excludable: structure of fields to include and exclude
        :type excludable: ExcludableItems
        :return: initialized through model without relation
        :rtype: "ModelRow"
        """
        model_cls = cls.Meta.model_fields[through_name].to
        table_prefix = cls.Meta.alias_manager.resolve_relation_alias(
            from_model=cls, relation_name=related
        )
        # remove relations on through field
        model_excludable = excludable.get(model_cls=model_cls, alias=table_prefix)
        model_excludable.set_values(
            value=model_cls.extract_related_names(), is_exclude=True
        )
        child_dict = model_cls.extract_prefixed_table_columns(
            item={}, row=row, excludable=excludable, table_prefix=table_prefix
        )
        child_dict["__excluded__"] = model_cls.get_names_to_exclude(
            excludable=excludable, alias=table_prefix
        )
        child = model_cls(**child_dict)  # type: ignore
        return child

    @classmethod
    def extract_prefixed_table_columns(
        cls,
        item: dict,
        row: ResultProxy,
        table_prefix: str,
        excludable: ExcludableItems,
    ) -> Dict:
        """
        Extracts own fields from raw sql result, using a given prefix.
        Prefix changes depending on the table's position in a join.

        If the table is a main table, there is no prefix.
        All joined tables have prefixes to allow duplicate column names,
        as well as duplicated joins to the same table from multiple different tables.

        Extracted fields populates the related dict later used to construct a Model.

        Used in Model.from_row and PrefetchQuery._populate_rows methods.

        :param excludable: structure of fields to include and exclude
        :type excludable: ExcludableItems
        :param item: dictionary of already populated nested models, otherwise empty dict
        :type item: Dict
        :param row: raw result row from the database
        :type row: sqlalchemy.engine.result.ResultProxy
        :param table_prefix: prefix of the table from AliasManager
        each pair of tables have own prefix (two of them depending on direction) -
        used in joins to allow multiple joins to the same table.
        :type table_prefix: str
        :return: dictionary with keys corresponding to model fields names
        and values are database values
        :rtype: Dict
        """
        selected_columns = cls.own_table_columns(
            model=cls, excludable=excludable, alias=table_prefix, use_alias=False
        )

        column_prefix = table_prefix + "_" if table_prefix else ""
        for column in cls.Meta.table.columns:
            alias = cls.get_column_name_from_alias(column.name)
            if alias not in item and alias in selected_columns:
                prefixed_name = f"{column_prefix}{column.name}"
                item[alias] = row[prefixed_name]

        return item

extract_prefixed_table_columns(item, row, table_prefix, excludable) classmethod

Extracts own fields from raw sql result, using a given prefix. Prefix changes depending on the table's position in a join.

If the table is a main table, there is no prefix. All joined tables have prefixes to allow duplicate column names, as well as duplicated joins to the same table from multiple different tables.

Extracted fields populates the related dict later used to construct a Model.

Used in Model.from_row and PrefetchQuery._populate_rows methods.

Parameters:

Name Type Description Default
excludable ExcludableItems

structure of fields to include and exclude

required
item dict

dictionary of already populated nested models, otherwise empty dict

required
row ResultProxy

raw result row from the database

required
table_prefix str

prefix of the table from AliasManager each pair of tables have own prefix (two of them depending on direction) - used in joins to allow multiple joins to the same table.

required

Returns:

Type Description
Dict

dictionary with keys corresponding to model fields names and values are database values

Source code in ormar\models\model_row.py
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
@classmethod
def extract_prefixed_table_columns(
    cls,
    item: dict,
    row: ResultProxy,
    table_prefix: str,
    excludable: ExcludableItems,
) -> Dict:
    """
    Extracts own fields from raw sql result, using a given prefix.
    Prefix changes depending on the table's position in a join.

    If the table is a main table, there is no prefix.
    All joined tables have prefixes to allow duplicate column names,
    as well as duplicated joins to the same table from multiple different tables.

    Extracted fields populates the related dict later used to construct a Model.

    Used in Model.from_row and PrefetchQuery._populate_rows methods.

    :param excludable: structure of fields to include and exclude
    :type excludable: ExcludableItems
    :param item: dictionary of already populated nested models, otherwise empty dict
    :type item: Dict
    :param row: raw result row from the database
    :type row: sqlalchemy.engine.result.ResultProxy
    :param table_prefix: prefix of the table from AliasManager
    each pair of tables have own prefix (two of them depending on direction) -
    used in joins to allow multiple joins to the same table.
    :type table_prefix: str
    :return: dictionary with keys corresponding to model fields names
    and values are database values
    :rtype: Dict
    """
    selected_columns = cls.own_table_columns(
        model=cls, excludable=excludable, alias=table_prefix, use_alias=False
    )

    column_prefix = table_prefix + "_" if table_prefix else ""
    for column in cls.Meta.table.columns:
        alias = cls.get_column_name_from_alias(column.name)
        if alias not in item and alias in selected_columns:
            prefixed_name = f"{column_prefix}{column.name}"
            item[alias] = row[prefixed_name]

    return item

from_row(row, source_model, select_related=None, related_models=None, related_field=None, excludable=None, current_relation_str='', proxy_source_model=None, used_prefixes=None) classmethod

Model method to convert raw sql row from database into ormar.Model instance. Traverses nested models if they were specified in select_related for query.

Called recurrently and returns model instance if it's present in the row. Note that it's processing one row at a time, so if there are duplicates of parent row that needs to be joined/combined (like parent row in sql join with 2+ child rows) instances populated in this method are later combined in the QuerySet. Other method working directly on raw database results is in prefetch_query, where rows are populated in a different way as they do not have nested models in result.

Parameters:

Name Type Description Default
used_prefixes List[str]

list of already extracted prefixes

None
proxy_source_model Optional[Type[Model]]

source model from which querysetproxy is constructed

None
excludable ExcludableItems

structure of fields to include and exclude

None
current_relation_str str

name of the relation field

''
source_model Type[Model]

model on which relation was defined

required
row ResultProxy

raw result row from the database

required
select_related List

list of names of related models fetched from database

None
related_models Any

list or dict of related models

None
related_field ForeignKeyField

field with relation declaration

None

Returns:

Type Description
Optional[Model]

returns model if model is populated from database

Source code in ormar\models\model_row.py
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 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
 77
 78
 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
@classmethod
def from_row(  # noqa: CFQ002
    cls,
    row: ResultProxy,
    source_model: Type["Model"],
    select_related: List = None,
    related_models: Any = None,
    related_field: "ForeignKeyField" = None,
    excludable: ExcludableItems = None,
    current_relation_str: str = "",
    proxy_source_model: Optional[Type["Model"]] = None,
    used_prefixes: List[str] = None,
) -> Optional["Model"]:
    """
    Model method to convert raw sql row from database into ormar.Model instance.
    Traverses nested models if they were specified in select_related for query.

    Called recurrently and returns model instance if it's present in the row.
    Note that it's processing one row at a time, so if there are duplicates of
    parent row that needs to be joined/combined
    (like parent row in sql join with 2+ child rows)
    instances populated in this method are later combined in the QuerySet.
    Other method working directly on raw database results is in prefetch_query,
    where rows are populated in a different way as they do not have
    nested models in result.

    :param used_prefixes: list of already extracted prefixes
    :type used_prefixes: List[str]
    :param proxy_source_model: source model from which querysetproxy is constructed
    :type proxy_source_model: Optional[Type["ModelRow"]]
    :param excludable: structure of fields to include and exclude
    :type excludable: ExcludableItems
    :param current_relation_str: name of the relation field
    :type current_relation_str: str
    :param source_model: model on which relation was defined
    :type source_model: Type[Model]
    :param row: raw result row from the database
    :type row: ResultProxy
    :param select_related: list of names of related models fetched from database
    :type select_related: List
    :param related_models: list or dict of related models
    :type related_models: Union[List, Dict]
    :param related_field: field with relation declaration
    :type related_field: ForeignKeyField
    :return: returns model if model is populated from database
    :rtype: Optional[Model]
    """
    item: Dict[str, Any] = {}
    select_related = select_related or []
    related_models = related_models or []
    table_prefix = ""
    used_prefixes = used_prefixes if used_prefixes is not None else []
    excludable = excludable or ExcludableItems()

    if select_related:
        related_models = group_related_list(select_related)

    if related_field:
        table_prefix = cls._process_table_prefix(
            source_model=source_model,
            current_relation_str=current_relation_str,
            related_field=related_field,
            used_prefixes=used_prefixes,
        )

    item = cls._populate_nested_models_from_row(
        item=item,
        row=row,
        related_models=related_models,
        excludable=excludable,
        current_relation_str=current_relation_str,
        source_model=source_model,  # type: ignore
        proxy_source_model=proxy_source_model,  # type: ignore
        table_prefix=table_prefix,
        used_prefixes=used_prefixes,
    )
    item = cls.extract_prefixed_table_columns(
        item=item, row=row, table_prefix=table_prefix, excludable=excludable
    )

    instance: Optional["Model"] = None
    if item.get(cls.Meta.pkname, None) is not None:
        item["__excluded__"] = cls.get_names_to_exclude(
            excludable=excludable, alias=table_prefix
        )
        instance = cast("Model", cls(**item))
        instance.set_save_status(True)
    return instance

NewBaseModel

Bases: pydantic.BaseModel, ModelTableProxy

Main base class of ormar Model. Inherits from pydantic BaseModel and has all mixins combined in ModelTableProxy. Constructed with ModelMetaclass which in turn also inherits pydantic metaclass.

Abstracts away all internals and helper functions, so final Model class has only the logic concerned with database connection and data persistence.

Source code in ormar\models\newbasemodel.py
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  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
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 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
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
class NewBaseModel(pydantic.BaseModel, ModelTableProxy, metaclass=ModelMetaclass):
    """
    Main base class of ormar Model.
    Inherits from pydantic BaseModel and has all mixins combined in ModelTableProxy.
    Constructed with ModelMetaclass which in turn also inherits pydantic metaclass.

    Abstracts away all internals and helper functions, so final Model class has only
    the logic concerned with database connection and data persistence.
    """

    __slots__ = (
        "_orm_id",
        "_orm_saved",
        "_orm",
        "_pk_column",
        "__pk_only__",
        "__cached_hash__",
    )

    if TYPE_CHECKING:  # pragma no cover
        pk: Any
        __model_fields__: Dict[str, BaseField]
        __table__: sqlalchemy.Table
        __pydantic_model__: Type[BaseModel]
        __pkname__: str
        __tablename__: str
        __metadata__: sqlalchemy.MetaData
        __database__: databases.Database
        __relation_map__: Optional[List[str]]
        __cached_hash__: Optional[int]
        _orm_relationship_manager: AliasManager
        _orm: RelationsManager
        _orm_id: int
        _orm_saved: bool
        _related_names: Optional[Set]
        _through_names: Optional[Set]
        _related_names_hash: str
        _choices_fields: Set
        _pydantic_fields: Set
        _quick_access_fields: Set
        _json_fields: Set
        _bytes_fields: Set
        Meta: ModelMeta

    # noinspection PyMissingConstructor
    def __init__(self, *args: Any, **kwargs: Any) -> None:  # type: ignore
        """
        Initializer that creates a new ormar Model that is also pydantic Model at the
        same time.

        Passed keyword arguments can be only field names and their corresponding values
        as those will be passed to pydantic validation that will complain if extra
        params are passed.

        If relations are defined each relation is expanded and children models are also
        initialized and validated. Relation from both sides is registered so you can
        access related models from both sides.

        Json fields are automatically loaded/dumped if needed.

        Models marked as abstract=True in internal Meta class cannot be initialized.

        Accepts also special __pk_only__ flag that indicates that Model is constructed
        only with primary key value (so no other fields, it's a child model on other
        Model), that causes skipping the validation, that's the only case when the
        validation can be skipped.

        Accepts also special __excluded__ parameter that contains a set of fields that
        should be explicitly set to None, as otherwise pydantic will try to populate
        them with their default values if default is set.

        :raises ModelError: if abstract model is initialized, model has ForwardRefs
         that has not been updated or unknown field is passed
        :param args: ignored args
        :type args: Any
        :param kwargs: keyword arguments - all fields values and some special params
        :type kwargs: Any
        """
        self._verify_model_can_be_initialized()
        self._initialize_internal_attributes()

        pk_only = kwargs.pop("__pk_only__", False)
        object.__setattr__(self, "__pk_only__", pk_only)

        new_kwargs, through_tmp_dict = self._process_kwargs(kwargs)

        if not pk_only:
            values, fields_set, validation_error = pydantic.validate_model(
                self, new_kwargs  # type: ignore
            )
            if validation_error:
                raise validation_error
        else:
            fields_set = {self.Meta.pkname}
            values = new_kwargs

        object.__setattr__(self, "__dict__", values)
        object.__setattr__(self, "__fields_set__", fields_set)

        # add back through fields
        new_kwargs.update(through_tmp_dict)
        model_fields = object.__getattribute__(self, "Meta").model_fields
        # register the columns models after initialization
        for related in self.extract_related_names().union(self.extract_through_names()):
            model_fields[related].expand_relationship(
                new_kwargs.get(related), self, to_register=True
            )

        if hasattr(self, "_init_private_attributes"):
            # introduced in pydantic 1.7
            self._init_private_attributes()

    def __setattr__(self, name: str, value: Any) -> None:  # noqa CCR001
        """
        Overwrites setattr in pydantic parent as otherwise descriptors are not called.

        :param name: name of the attribute to set
        :type name: str
        :param value: value of the attribute to set
        :type value: Any
        :return: None
        :rtype: None
        """
        prev_hash = hash(self)

        if hasattr(self, name):
            object.__setattr__(self, name, value)
        else:
            # let pydantic handle errors for unknown fields
            super().__setattr__(name, value)

        # In this case, the hash could have changed, so update it
        if name == self.Meta.pkname or self.pk is None:
            object.__setattr__(self, "__cached_hash__", None)
            new_hash = hash(self)

            if prev_hash != new_hash:
                self._update_relation_cache(prev_hash, new_hash)

    def __getattr__(self, item: str) -> Any:
        """
        Used only to silence mypy errors for Through models and reverse relations.
        Not used in real life as in practice calls are intercepted
        by RelationDescriptors

        :param item: name of attribute
        :type item: str
        :return: Any
        :rtype: Any
        """
        return super().__getattribute__(item)

    def __getstate__(self) -> Dict[Any, Any]:
        state = super().__getstate__()
        self_dict = self.dict()
        state["__dict__"].update(**self_dict)
        return state

    def __setstate__(self, state: Dict[Any, Any]) -> None:
        relations = {
            k: v
            for k, v in state["__dict__"].items()
            if k in self.extract_related_names()
        }
        basic_state = {
            k: v
            for k, v in state["__dict__"].items()
            if k not in self.extract_related_names()
        }
        state["__dict__"] = basic_state
        super().__setstate__(state)
        self._initialize_internal_attributes()
        for name, value in relations.items():
            setattr(self, name, value)

    def _update_relation_cache(self, prev_hash: int, new_hash: int) -> None:
        """
        Update all relation proxy caches with different hash if we have changed

        :param prev_hash: The previous hash to update
        :type prev_hash: int
        :param new_hash: The hash to update to
        :type new_hash: int
        """

        def _update_cache(relations: List[Relation], recurse: bool = True) -> None:
            for relation in relations:
                relation_proxy = relation.get()

                if hasattr(relation_proxy, "update_cache"):
                    relation_proxy.update_cache(prev_hash, new_hash)  # type: ignore
                elif recurse and hasattr(relation_proxy, "_orm"):
                    _update_cache(
                        relation_proxy._orm._relations.values(),  # type: ignore
                        recurse=False,
                    )

        _update_cache(list(self._orm._relations.values()))

    def _internal_set(self, name: str, value: Any) -> None:
        """
        Delegates call to pydantic.

        :param name: name of param
        :type name: str
        :param value: value to set
        :type value: Any
        """
        super().__setattr__(name, value)

    def _verify_model_can_be_initialized(self) -> None:
        """
        Raises exception if model is abstract or has ForwardRefs in relation fields.

        :return: None
        :rtype: None
        """
        if self.Meta.abstract:
            raise ModelError(f"You cannot initialize abstract model {self.get_name()}")
        if self.Meta.requires_ref_update:
            raise ModelError(
                f"Model {self.get_name()} has not updated "
                f"ForwardRefs. \nBefore using the model you "
                f"need to call update_forward_refs()."
            )

    def _process_kwargs(self, kwargs: Dict) -> Tuple[Dict, Dict]:  # noqa: CCR001
        """
        Initializes nested models.

        Removes property_fields

        Checks if field is in the model fields or pydatnic fields.

        Nullifies fields that should be excluded.

        Extracts through models from kwargs into temporary dict.

        :param kwargs: passed to init keyword arguments
        :type kwargs: Dict
        :return: modified kwargs
        :rtype: Tuple[Dict, Dict]
        """
        property_fields = self.Meta.property_fields
        model_fields = self.Meta.model_fields
        pydantic_fields = set(self.__fields__.keys())

        # remove property fields
        for prop_filed in property_fields:
            kwargs.pop(prop_filed, None)

        excluded: Set[str] = kwargs.pop("__excluded__", set())
        if "pk" in kwargs:
            kwargs[self.Meta.pkname] = kwargs.pop("pk")

        # extract through fields
        through_tmp_dict = dict()
        for field_name in self.extract_through_names():
            through_tmp_dict[field_name] = kwargs.pop(field_name, None)

        kwargs = self._remove_extra_parameters_if_they_should_be_ignored(
            kwargs=kwargs, model_fields=model_fields, pydantic_fields=pydantic_fields
        )
        try:
            new_kwargs: Dict[str, Any] = {
                k: self._convert_to_bytes(
                    k,
                    self._convert_json(
                        k,
                        model_fields[k].expand_relationship(v, self, to_register=False)
                        if k in model_fields
                        else (v if k in pydantic_fields else model_fields[k]),
                    ),
                )
                for k, v in kwargs.items()
            }
        except KeyError as e:
            raise ModelError(
                f"Unknown field '{e.args[0]}' for model {self.get_name(lower=False)}"
            )

        # explicitly set None to excluded fields
        # as pydantic populates them with default if set
        for field_to_nullify in excluded:
            new_kwargs[field_to_nullify] = None

        return new_kwargs, through_tmp_dict

    def _remove_extra_parameters_if_they_should_be_ignored(
        self, kwargs: Dict, model_fields: Dict, pydantic_fields: Set
    ) -> Dict:
        """
        Removes the extra fields from kwargs if they should be ignored.

        :param kwargs: passed arguments
        :type kwargs: Dict
        :param model_fields: dictionary of model fields
        :type model_fields: Dict
        :param pydantic_fields: set of pydantic fields names
        :type pydantic_fields: Set
        :return: dict without extra fields
        :rtype: Dict
        """
        if self.Meta.extra == Extra.ignore:
            kwargs = {
                k: v
                for k, v in kwargs.items()
                if k in model_fields or k in pydantic_fields
            }
        return kwargs

    def _initialize_internal_attributes(self) -> None:
        """
        Initializes internal attributes during __init__()
        :rtype: None
        """
        # object.__setattr__(self, "_orm_id", uuid.uuid4().hex)
        object.__setattr__(self, "_orm_saved", False)
        object.__setattr__(self, "_pk_column", None)
        object.__setattr__(
            self,
            "_orm",
            RelationsManager(
                related_fields=self.extract_related_fields(), owner=cast("Model", self)
            ),
        )

    def __eq__(self, other: object) -> bool:
        """
        Compares other model to this model. when == is called.
        :param other: other model to compare
        :type other: object
        :return: result of comparison
        :rtype: bool
        """
        if isinstance(other, NewBaseModel):
            return self.__same__(other)
        return super().__eq__(other)  # pragma no cover

    def __hash__(self) -> int:
        if getattr(self, "__cached_hash__", None) is not None:
            return self.__cached_hash__ or 0

        if self.pk is not None:
            ret = hash(str(self.pk) + self.__class__.__name__)
        else:
            vals = {
                k: v
                for k, v in self.__dict__.items()
                if k not in self.extract_related_names()
            }
            ret = hash(str(vals) + self.__class__.__name__)

        object.__setattr__(self, "__cached_hash__", ret)
        return ret

    def __same__(self, other: "NewBaseModel") -> bool:
        """
        Used by __eq__, compares other model to this model.
        Compares:
        * _orm_ids,
        * primary key values if it's set
        * dictionary of own fields (excluding relations)
        :param other: model to compare to
        :type other: NewBaseModel
        :return: result of comparison
        :rtype: bool
        """
        if (self.pk is None and other.pk is not None) or (
            self.pk is not None and other.pk is None
        ):
            return False
        else:
            return hash(self) == other.__hash__()

    def _copy_and_set_values(
        self: "NewBaseModel", values: "DictStrAny", fields_set: "SetStr", *, deep: bool
    ) -> "NewBaseModel":
        """
        Overwrite related models values with dict representation to avoid infinite
        recursion through related fields.
        """
        self_dict = values
        self_dict.update(self.dict(exclude_list=True))
        return cast(
            "NewBaseModel",
            super()._copy_and_set_values(
                values=self_dict, fields_set=fields_set, deep=deep
            ),
        )

    @classmethod
    def get_name(cls, lower: bool = True) -> str:
        """
        Returns name of the Model class, by default lowercase.

        :param lower: flag if name should be set to lowercase
        :type lower: bool
        :return: name of the model
        :rtype: str
        """
        name = cls.__name__
        if lower:
            name = name.lower()
        return name

    @property
    def pk_column(self) -> sqlalchemy.Column:
        """
        Retrieves primary key sqlalchemy column from models Meta.table.
        Each model has to have primary key.
        Only one primary key column is allowed.

        :return: primary key sqlalchemy column
        :rtype: sqlalchemy.Column
        """
        if object.__getattribute__(self, "_pk_column") is not None:
            return object.__getattribute__(self, "_pk_column")
        pk_columns = self.Meta.table.primary_key.columns.values()
        pk_col = pk_columns[0]
        object.__setattr__(self, "_pk_column", pk_col)
        return pk_col

    @property
    def saved(self) -> bool:
        """Saved status of the model. Changed by setattr and loading from db"""
        return self._orm_saved

    @property
    def signals(self) -> "SignalEmitter":
        """Exposes signals from model Meta"""
        return self.Meta.signals

    @classmethod
    def pk_type(cls) -> Any:
        """Shortcut to models primary key field type"""
        return cls.Meta.model_fields[cls.Meta.pkname].__type__

    @classmethod
    def db_backend_name(cls) -> str:
        """Shortcut to database dialect,
        cause some dialect require different treatment"""
        return cls.Meta.database._backend._dialect.name

    def remove(self, parent: "Model", name: str) -> None:
        """Removes child from relation with given name in RelationshipManager"""
        self._orm.remove_parent(self, parent, name)

    def set_save_status(self, status: bool) -> None:
        """Sets value of the save status"""
        object.__setattr__(self, "_orm_saved", status)

    @classmethod
    def get_properties(
        cls, include: Union[Set, Dict, None], exclude: Union[Set, Dict, None]
    ) -> Set[str]:
        """
        Returns a set of names of functions/fields decorated with
        @property_field decorator.

        They are added to dictionary when called directly and therefore also are
        present in fastapi responses.

        :param include: fields to include
        :type include: Union[Set, Dict, None]
        :param exclude: fields to exclude
        :type exclude: Union[Set, Dict, None]
        :return: set of property fields names
        :rtype: Set[str]
        """

        props = cls.Meta.property_fields
        if include:
            props = {prop for prop in props if prop in include}
        if exclude:
            props = {prop for prop in props if prop not in exclude}
        return props

    @classmethod
    def update_forward_refs(cls, **localns: Any) -> None:
        """
        Processes fields that are ForwardRef and need to be evaluated into actual
        models.

        Expands relationships, register relation in alias manager and substitutes
        sqlalchemy columns with new ones with proper column type (null before).

        Populates Meta table of the Model which is left empty before.

        Sets self_reference flag on models that links to themselves.

        Calls the pydantic method to evaluate pydantic fields.

        :param localns: local namespace
        :type localns: Any
        :return: None
        :rtype: None
        """
        globalns = sys.modules[cls.__module__].__dict__.copy()
        globalns.setdefault(cls.__name__, cls)
        fields_to_check = cls.Meta.model_fields.copy()
        for field in fields_to_check.values():
            if field.has_unresolved_forward_refs():
                field = cast(ForeignKeyField, field)
                field.evaluate_forward_ref(globalns=globalns, localns=localns)
                field.set_self_reference_flag()
                if field.is_multi and not field.through:
                    field = cast(ormar.ManyToManyField, field)
                    field.create_default_through_model()
                expand_reverse_relationship(model_field=field)
                register_relation_in_alias_manager(field=field)
                update_column_definition(model=cls, field=field)
        populate_meta_sqlalchemy_table_if_required(meta=cls.Meta)
        super().update_forward_refs(**localns)
        cls.Meta.requires_ref_update = False

    @staticmethod
    def _get_not_excluded_fields(
        fields: Union[List, Set], include: Optional[Dict], exclude: Optional[Dict]
    ) -> List:
        """
        Returns related field names applying on them include and exclude set.

        :param include: fields to include
        :type include: Union[Set, Dict, None]
        :param exclude: fields to exclude
        :type exclude: Union[Set, Dict, None]
        :return:
        :rtype: List of fields with relations that is not excluded
        """
        fields = [*fields] if not isinstance(fields, list) else fields
        if include:
            fields = [field for field in fields if field in include]
        if exclude:
            fields = [
                field
                for field in fields
                if field not in exclude
                or (
                    exclude.get(field) is not Ellipsis
                    and exclude.get(field) != {"__all__"}
                )
            ]
        return fields

    @staticmethod
    def _extract_nested_models_from_list(
        relation_map: Dict,
        models: MutableSequence,
        include: Union[Set, Dict, None],
        exclude: Union[Set, Dict, None],
        exclude_primary_keys: bool,
        exclude_through_models: bool,
    ) -> List:
        """
        Converts list of models into list of dictionaries.

        :param models: List of models
        :type models: List
        :param include: fields to include
        :type include: Union[Set, Dict, None]
        :param exclude: fields to exclude
        :type exclude: Union[Set, Dict, None]
        :return: list of models converted to dictionaries
        :rtype: List[Dict]
        """
        result = []
        for model in models:
            try:
                result.append(
                    model.dict(
                        relation_map=relation_map,
                        include=include,
                        exclude=exclude,
                        exclude_primary_keys=exclude_primary_keys,
                        exclude_through_models=exclude_through_models,
                    )
                )
            except ReferenceError:  # pragma no cover
                continue
        return result

    @classmethod
    def _skip_ellipsis(
        cls, items: Union[Set, Dict, None], key: str, default_return: Any = None
    ) -> Union[Set, Dict, None]:
        """
        Helper to traverse the include/exclude dictionaries.
        In dict() Ellipsis should be skipped as it indicates all fields required
        and not the actual set/dict with fields names.

        :param items: current include/exclude value
        :type items: Union[Set, Dict, None]
        :param key: key for nested relations to check
        :type key: str
        :return: nested value of the items
        :rtype: Union[Set, Dict, None]
        """
        result = cls.get_child(items, key)
        return result if result is not Ellipsis else default_return

    @staticmethod
    def _convert_all(items: Union[Set, Dict, None]) -> Union[Set, Dict, None]:
        """
        Helper to convert __all__ pydantic special index to ormar which does not
        support index based exclusions.

        :param items: current include/exclude value
        :type items: Union[Set, Dict, None]
        """
        if isinstance(items, dict) and "__all__" in items:
            return items.get("__all__")
        return items

    def _extract_nested_models(  # noqa: CCR001, CFQ002
        self,
        relation_map: Dict,
        dict_instance: Dict,
        include: Optional[Dict],
        exclude: Optional[Dict],
        exclude_primary_keys: bool,
        exclude_through_models: bool,
        exclude_list: bool,
    ) -> Dict:
        """
        Traverse nested models and converts them into dictionaries.
        Calls itself recursively if needed.

        :param nested: flag if current instance is nested
        :type nested: bool
        :param dict_instance: current instance dict
        :type dict_instance: Dict
        :param include: fields to include
        :type include: Optional[Dict]
        :param exclude: fields to exclude
        :type exclude: Optional[Dict]
        :param exclude: whether to exclude lists
        :type exclude: bool
        :return: current model dict with child models converted to dictionaries
        :rtype: Dict
        """
        fields = self._get_not_excluded_fields(
            fields=self.extract_related_names(), include=include, exclude=exclude
        )

        for field in fields:
            if not relation_map or field not in relation_map:
                continue
            try:
                nested_model = getattr(self, field)
                if isinstance(nested_model, MutableSequence):
                    if exclude_list:
                        continue

                    dict_instance[field] = self._extract_nested_models_from_list(
                        relation_map=self._skip_ellipsis(  # type: ignore
                            relation_map, field, default_return=dict()
                        ),
                        models=nested_model,
                        include=self._convert_all(self._skip_ellipsis(include, field)),
                        exclude=self._convert_all(self._skip_ellipsis(exclude, field)),
                        exclude_primary_keys=exclude_primary_keys,
                        exclude_through_models=exclude_through_models,
                    )
                elif nested_model is not None:

                    dict_instance[field] = nested_model.dict(
                        relation_map=self._skip_ellipsis(
                            relation_map, field, default_return=dict()
                        ),
                        include=self._convert_all(self._skip_ellipsis(include, field)),
                        exclude=self._convert_all(self._skip_ellipsis(exclude, field)),
                        exclude_primary_keys=exclude_primary_keys,
                        exclude_through_models=exclude_through_models,
                    )
                else:
                    dict_instance[field] = None
            except ReferenceError:
                dict_instance[field] = None
        return dict_instance

    def dict(  # type: ignore # noqa A003
        self,
        *,
        include: Union[Set, Dict] = None,
        exclude: Union[Set, Dict] = None,
        by_alias: bool = False,
        skip_defaults: bool = None,
        exclude_unset: bool = False,
        exclude_defaults: bool = False,
        exclude_none: bool = False,
        exclude_primary_keys: bool = False,
        exclude_through_models: bool = False,
        exclude_list: bool = False,
        relation_map: Dict = None,
    ) -> "DictStrAny":  # noqa: A003'
        """

        Generate a dictionary representation of the model,
        optionally specifying which fields to include or exclude.

        Nested models are also parsed to dictionaries.

        Additionally fields decorated with @property_field are also added.

        :param exclude_through_models: flag to exclude through models from dict
        :type exclude_through_models: bool
        :param exclude_primary_keys: flag to exclude primary keys from dict
        :type exclude_primary_keys: bool
        :param include: fields to include
        :type include: Union[Set, Dict, None]
        :param exclude: fields to exclude
        :type exclude: Union[Set, Dict, None]
        :param by_alias: flag to get values by alias - passed to pydantic
        :type by_alias: bool
        :param skip_defaults: flag to not set values - passed to pydantic
        :type skip_defaults: bool
        :param exclude_unset: flag to exclude not set values - passed to pydantic
        :type exclude_unset: bool
        :param exclude_defaults: flag to exclude default values - passed to pydantic
        :type exclude_defaults: bool
        :param exclude_none: flag to exclude None values - passed to pydantic
        :type exclude_none: bool
        :param exclude_list: flag to exclude lists of nested values models from dict
        :type exclude_list: bool
        :param relation_map: map of the relations to follow to avoid circural deps
        :type relation_map: Dict
        :return:
        :rtype:
        """
        pydantic_exclude = self._update_excluded_with_related(exclude)
        pydantic_exclude = self._update_excluded_with_pks_and_through(
            exclude=pydantic_exclude,
            exclude_primary_keys=exclude_primary_keys,
            exclude_through_models=exclude_through_models,
        )
        dict_instance = super().dict(
            include=include,
            exclude=pydantic_exclude,
            by_alias=by_alias,
            skip_defaults=skip_defaults,
            exclude_unset=exclude_unset,
            exclude_defaults=exclude_defaults,
            exclude_none=exclude_none,
        )

        dict_instance = {
            k: self._convert_bytes_to_str(column_name=k, value=v)
            for k, v in dict_instance.items()
        }

        if include and isinstance(include, Set):
            include = translate_list_to_dict(include)
        if exclude and isinstance(exclude, Set):
            exclude = translate_list_to_dict(exclude)

        relation_map = (
            relation_map
            if relation_map is not None
            else translate_list_to_dict(self._iterate_related_models())
        )
        pk_only = getattr(self, "__pk_only__", False)
        if relation_map and not pk_only:
            dict_instance = self._extract_nested_models(
                relation_map=relation_map,
                dict_instance=dict_instance,
                include=include,  # type: ignore
                exclude=exclude,  # type: ignore
                exclude_primary_keys=exclude_primary_keys,
                exclude_through_models=exclude_through_models,
                exclude_list=exclude_list,
            )

        # include model properties as fields in dict
        if object.__getattribute__(self, "Meta").property_fields:
            props = self.get_properties(include=include, exclude=exclude)
            if props:
                dict_instance.update({prop: getattr(self, prop) for prop in props})

        return dict_instance

    def json(  # type: ignore # noqa A003
        self,
        *,
        include: Union[Set, Dict] = None,
        exclude: Union[Set, Dict] = None,
        by_alias: bool = False,
        skip_defaults: bool = None,
        exclude_unset: bool = False,
        exclude_defaults: bool = False,
        exclude_none: bool = False,
        encoder: Optional[Callable[[Any], Any]] = None,
        exclude_primary_keys: bool = False,
        exclude_through_models: bool = False,
        **dumps_kwargs: Any,
    ) -> str:
        """
        Generate a JSON representation of the model, `include` and `exclude`
        arguments as per `dict()`.

        `encoder` is an optional function to supply as `default` to json.dumps(),
        other arguments as per `json.dumps()`.
        """
        if skip_defaults is not None:  # pragma: no cover
            warnings.warn(
                f'{self.__class__.__name__}.json(): "skip_defaults" is deprecated '
                f'and replaced by "exclude_unset"',
                DeprecationWarning,
            )
            exclude_unset = skip_defaults
        encoder = cast(Callable[[Any], Any], encoder or self.__json_encoder__)
        data = self.dict(
            include=include,
            exclude=exclude,
            by_alias=by_alias,
            exclude_unset=exclude_unset,
            exclude_defaults=exclude_defaults,
            exclude_none=exclude_none,
            exclude_primary_keys=exclude_primary_keys,
            exclude_through_models=exclude_through_models,
        )
        if self.__custom_root_type__:  # pragma: no cover
            data = data["__root__"]
        return self.__config__.json_dumps(data, default=encoder, **dumps_kwargs)

    @classmethod
    def construct(
        cls: Type["T"], _fields_set: Optional["SetStr"] = None, **values: Any
    ) -> "T":
        own_values = {
            k: v for k, v in values.items() if k not in cls.extract_related_names()
        }
        model = cls.__new__(cls)
        fields_values: Dict[str, Any] = {}
        for name, field in cls.__fields__.items():
            if name in own_values:
                fields_values[name] = own_values[name]
            elif not field.required:
                fields_values[name] = field.get_default()
        fields_values.update(own_values)
        object.__setattr__(model, "__dict__", fields_values)
        model._initialize_internal_attributes()
        cls._construct_relations(model=model, values=values)
        if _fields_set is None:
            _fields_set = set(values.keys())
        object.__setattr__(model, "__fields_set__", _fields_set)
        return model

    @classmethod
    def _construct_relations(cls: Type["T"], model: "T", values: Dict) -> None:
        present_relations = [
            relation for relation in cls.extract_related_names() if relation in values
        ]
        for relation in present_relations:
            value_to_set = values[relation]
            if not isinstance(value_to_set, list):
                value_to_set = [value_to_set]
            relation_field = cls.Meta.model_fields[relation]
            relation_value = [
                relation_field.expand_relationship(x, model, to_register=False)
                for x in value_to_set
                if x is not None
            ]

            for child in relation_value:
                model._orm.add(
                    parent=cast("Model", child),
                    child=cast("Model", model),
                    field=cast("ForeignKeyField", relation_field),
                )

    def update_from_dict(self, value_dict: Dict) -> "NewBaseModel":
        """
        Updates self with values of fields passed in the dictionary.

        :param value_dict: dictionary of fields names and values
        :type value_dict: Dict
        :return: self
        :rtype: NewBaseModel
        """
        for key, value in value_dict.items():
            setattr(self, key, value)
        return self

    def _convert_to_bytes(self, column_name: str, value: Any) -> Union[str, Dict]:
        """
        Converts value to bytes from string

        :param column_name: name of the field
        :type column_name: str
        :param value: value fo the field
        :type value: Any
        :return: converted value if needed, else original value
        :rtype: Any
        """
        if column_name not in self._bytes_fields:
            return value
        field = self.Meta.model_fields[column_name]
        if not isinstance(value, bytes) and value is not None:
            if field.represent_as_base64_str:
                value = base64.b64decode(value)
            else:
                value = value.encode("utf-8")
        return value

    def _convert_bytes_to_str(self, column_name: str, value: Any) -> Union[str, Dict]:
        """
        Converts value to str from bytes for represent_as_base64_str columns.

        :param column_name: name of the field
        :type column_name: str
        :param value: value fo the field
        :type value: Any
        :return: converted value if needed, else original value
        :rtype: Any
        """
        if column_name not in self._bytes_fields:
            return value
        field = self.Meta.model_fields[column_name]
        if (
            value is not None
            and not isinstance(value, str)
            and field.represent_as_base64_str
        ):
            return base64.b64encode(value).decode()
        return value

    def _convert_json(self, column_name: str, value: Any) -> Union[str, Dict, None]:
        """
        Converts value to/from json if needed (for Json columns).

        :param column_name: name of the field
        :type column_name: str
        :param value: value fo the field
        :type value: Any
        :return: converted value if needed, else original value
        :rtype: Any
        """
        if column_name not in self._json_fields:
            return value
        return encode_json(value)

    def _extract_own_model_fields(self) -> Dict:
        """
        Returns a dictionary with field names and values for fields that are not
        relations fields (ForeignKey, ManyToMany etc.)

        :return: dictionary of fields names and values.
        :rtype: Dict
        """
        related_names = self.extract_related_names()
        self_fields = {k: v for k, v in self.__dict__.items() if k not in related_names}
        return self_fields

    def _extract_model_db_fields(self) -> Dict:
        """
        Returns a dictionary with field names and values for fields that are stored in
        current model's table.

        That includes own non-relational fields ang foreign key fields.

        :return: dictionary of fields names and values.
        :rtype: Dict
        """
        # TODO: Cache this dictionary?
        self_fields = self._extract_own_model_fields()
        self_fields = {
            k: v
            for k, v in self_fields.items()
            if self.get_column_alias(k) in self.Meta.table.columns
        }
        for field in self._extract_db_related_names():
            relation_field = self.Meta.model_fields[field]
            target_pk_name = relation_field.to.Meta.pkname
            target_field = getattr(self, field)
            self_fields[field] = getattr(target_field, target_pk_name, None)
            if not relation_field.nullable and not self_fields[field]:
                raise ModelPersistenceError(
                    f"You cannot save {relation_field.to.get_name()} "
                    f"model without pk set!"
                )
        return self_fields

    def get_relation_model_id(self, target_field: "BaseField") -> Optional[int]:
        """
        Returns an id of the relation side model to use in prefetch query.

        :param target_field: field with relation definition
        :type target_field: "BaseField"
        :return: value of pk if set
        :rtype: Optional[int]
        """
        if target_field.virtual or target_field.is_multi:
            return self.pk
        related_name = target_field.name
        related_model = getattr(self, related_name)
        return None if not related_model else related_model.pk

pk_column: sqlalchemy.Column property

Retrieves primary key sqlalchemy column from models Meta.table. Each model has to have primary key. Only one primary key column is allowed.

Returns:

Type Description
sqlalchemy.Column

primary key sqlalchemy column

saved: bool property

Saved status of the model. Changed by setattr and loading from db

signals: SignalEmitter property

Exposes signals from model Meta

__eq__(other)

Compares other model to this model. when == is called.

Parameters:

Name Type Description Default
other object

other model to compare

required

Returns:

Type Description
bool

result of comparison

Source code in ormar\models\newbasemodel.py
387
388
389
390
391
392
393
394
395
396
397
def __eq__(self, other: object) -> bool:
    """
    Compares other model to this model. when == is called.
    :param other: other model to compare
    :type other: object
    :return: result of comparison
    :rtype: bool
    """
    if isinstance(other, NewBaseModel):
        return self.__same__(other)
    return super().__eq__(other)  # pragma no cover

__getattr__(item)

Used only to silence mypy errors for Through models and reverse relations. Not used in real life as in practice calls are intercepted by RelationDescriptors

Parameters:

Name Type Description Default
item str

name of attribute

required

Returns:

Type Description
Any

Any

Source code in ormar\models\newbasemodel.py
199
200
201
202
203
204
205
206
207
208
209
210
def __getattr__(self, item: str) -> Any:
    """
    Used only to silence mypy errors for Through models and reverse relations.
    Not used in real life as in practice calls are intercepted
    by RelationDescriptors

    :param item: name of attribute
    :type item: str
    :return: Any
    :rtype: Any
    """
    return super().__getattribute__(item)

__init__(*args, **kwargs)

Initializer that creates a new ormar Model that is also pydantic Model at the same time.

Passed keyword arguments can be only field names and their corresponding values as those will be passed to pydantic validation that will complain if extra params are passed.

If relations are defined each relation is expanded and children models are also initialized and validated. Relation from both sides is registered so you can access related models from both sides.

Json fields are automatically loaded/dumped if needed.

Models marked as abstract=True in internal Meta class cannot be initialized.

Accepts also special pk_only flag that indicates that Model is constructed only with primary key value (so no other fields, it's a child model on other Model), that causes skipping the validation, that's the only case when the validation can be skipped.

Accepts also special excluded parameter that contains a set of fields that should be explicitly set to None, as otherwise pydantic will try to populate them with their default values if default is set.

Parameters:

Name Type Description Default
args Any

ignored args

()
kwargs Any

keyword arguments - all fields values and some special params

{}

Raises:

Type Description
ModelError

if abstract model is initialized, model has ForwardRefs that has not been updated or unknown field is passed

Source code in ormar\models\newbasemodel.py
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
def __init__(self, *args: Any, **kwargs: Any) -> None:  # type: ignore
    """
    Initializer that creates a new ormar Model that is also pydantic Model at the
    same time.

    Passed keyword arguments can be only field names and their corresponding values
    as those will be passed to pydantic validation that will complain if extra
    params are passed.

    If relations are defined each relation is expanded and children models are also
    initialized and validated. Relation from both sides is registered so you can
    access related models from both sides.

    Json fields are automatically loaded/dumped if needed.

    Models marked as abstract=True in internal Meta class cannot be initialized.

    Accepts also special __pk_only__ flag that indicates that Model is constructed
    only with primary key value (so no other fields, it's a child model on other
    Model), that causes skipping the validation, that's the only case when the
    validation can be skipped.

    Accepts also special __excluded__ parameter that contains a set of fields that
    should be explicitly set to None, as otherwise pydantic will try to populate
    them with their default values if default is set.

    :raises ModelError: if abstract model is initialized, model has ForwardRefs
     that has not been updated or unknown field is passed
    :param args: ignored args
    :type args: Any
    :param kwargs: keyword arguments - all fields values and some special params
    :type kwargs: Any
    """
    self._verify_model_can_be_initialized()
    self._initialize_internal_attributes()

    pk_only = kwargs.pop("__pk_only__", False)
    object.__setattr__(self, "__pk_only__", pk_only)

    new_kwargs, through_tmp_dict = self._process_kwargs(kwargs)

    if not pk_only:
        values, fields_set, validation_error = pydantic.validate_model(
            self, new_kwargs  # type: ignore
        )
        if validation_error:
            raise validation_error
    else:
        fields_set = {self.Meta.pkname}
        values = new_kwargs

    object.__setattr__(self, "__dict__", values)
    object.__setattr__(self, "__fields_set__", fields_set)

    # add back through fields
    new_kwargs.update(through_tmp_dict)
    model_fields = object.__getattribute__(self, "Meta").model_fields
    # register the columns models after initialization
    for related in self.extract_related_names().union(self.extract_through_names()):
        model_fields[related].expand_relationship(
            new_kwargs.get(related), self, to_register=True
        )

    if hasattr(self, "_init_private_attributes"):
        # introduced in pydantic 1.7
        self._init_private_attributes()

__same__(other)

Used by eq, compares other model to this model. Compares: * _orm_ids, * primary key values if it's set * dictionary of own fields (excluding relations)

Parameters:

Name Type Description Default
other NewBaseModel

model to compare to

required

Returns:

Type Description
bool

result of comparison

Source code in ormar\models\newbasemodel.py
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
def __same__(self, other: "NewBaseModel") -> bool:
    """
    Used by __eq__, compares other model to this model.
    Compares:
    * _orm_ids,
    * primary key values if it's set
    * dictionary of own fields (excluding relations)
    :param other: model to compare to
    :type other: NewBaseModel
    :return: result of comparison
    :rtype: bool
    """
    if (self.pk is None and other.pk is not None) or (
        self.pk is not None and other.pk is None
    ):
        return False
    else:
        return hash(self) == other.__hash__()

__setattr__(name, value)

Overwrites setattr in pydantic parent as otherwise descriptors are not called.

Parameters:

Name Type Description Default
name str

name of the attribute to set

required
value Any

value of the attribute to set

required

Returns:

Type Description
None

None

Source code in ormar\models\newbasemodel.py
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
def __setattr__(self, name: str, value: Any) -> None:  # noqa CCR001
    """
    Overwrites setattr in pydantic parent as otherwise descriptors are not called.

    :param name: name of the attribute to set
    :type name: str
    :param value: value of the attribute to set
    :type value: Any
    :return: None
    :rtype: None
    """
    prev_hash = hash(self)

    if hasattr(self, name):
        object.__setattr__(self, name, value)
    else:
        # let pydantic handle errors for unknown fields
        super().__setattr__(name, value)

    # In this case, the hash could have changed, so update it
    if name == self.Meta.pkname or self.pk is None:
        object.__setattr__(self, "__cached_hash__", None)
        new_hash = hash(self)

        if prev_hash != new_hash:
            self._update_relation_cache(prev_hash, new_hash)

db_backend_name() classmethod

Shortcut to database dialect, cause some dialect require different treatment

Source code in ormar\models\newbasemodel.py
498
499
500
501
502
@classmethod
def db_backend_name(cls) -> str:
    """Shortcut to database dialect,
    cause some dialect require different treatment"""
    return cls.Meta.database._backend._dialect.name

dict(*, include=None, exclude=None, by_alias=False, skip_defaults=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, exclude_primary_keys=False, exclude_through_models=False, exclude_list=False, relation_map=None)

Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

Nested models are also parsed to dictionaries.

Additionally fields decorated with @property_field are also added.

Parameters:

Name Type Description Default
exclude_through_models bool

flag to exclude through models from dict

False
exclude_primary_keys bool

flag to exclude primary keys from dict

False
include Union[Set, Dict]

fields to include

None
exclude Union[Set, Dict]

fields to exclude

None
by_alias bool

flag to get values by alias - passed to pydantic

False
skip_defaults bool

flag to not set values - passed to pydantic

None
exclude_unset bool

flag to exclude not set values - passed to pydantic

False
exclude_defaults bool

flag to exclude default values - passed to pydantic

False
exclude_none bool

flag to exclude None values - passed to pydantic

False
exclude_list bool

flag to exclude lists of nested values models from dict

False
relation_map Dict

map of the relations to follow to avoid circural deps

None

Returns:

Type Description
Source code in ormar\models\newbasemodel.py
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
def dict(  # type: ignore # noqa A003
    self,
    *,
    include: Union[Set, Dict] = None,
    exclude: Union[Set, Dict] = None,
    by_alias: bool = False,
    skip_defaults: bool = None,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    exclude_primary_keys: bool = False,
    exclude_through_models: bool = False,
    exclude_list: bool = False,
    relation_map: Dict = None,
) -> "DictStrAny":  # noqa: A003'
    """

    Generate a dictionary representation of the model,
    optionally specifying which fields to include or exclude.

    Nested models are also parsed to dictionaries.

    Additionally fields decorated with @property_field are also added.

    :param exclude_through_models: flag to exclude through models from dict
    :type exclude_through_models: bool
    :param exclude_primary_keys: flag to exclude primary keys from dict
    :type exclude_primary_keys: bool
    :param include: fields to include
    :type include: Union[Set, Dict, None]
    :param exclude: fields to exclude
    :type exclude: Union[Set, Dict, None]
    :param by_alias: flag to get values by alias - passed to pydantic
    :type by_alias: bool
    :param skip_defaults: flag to not set values - passed to pydantic
    :type skip_defaults: bool
    :param exclude_unset: flag to exclude not set values - passed to pydantic
    :type exclude_unset: bool
    :param exclude_defaults: flag to exclude default values - passed to pydantic
    :type exclude_defaults: bool
    :param exclude_none: flag to exclude None values - passed to pydantic
    :type exclude_none: bool
    :param exclude_list: flag to exclude lists of nested values models from dict
    :type exclude_list: bool
    :param relation_map: map of the relations to follow to avoid circural deps
    :type relation_map: Dict
    :return:
    :rtype:
    """
    pydantic_exclude = self._update_excluded_with_related(exclude)
    pydantic_exclude = self._update_excluded_with_pks_and_through(
        exclude=pydantic_exclude,
        exclude_primary_keys=exclude_primary_keys,
        exclude_through_models=exclude_through_models,
    )
    dict_instance = super().dict(
        include=include,
        exclude=pydantic_exclude,
        by_alias=by_alias,
        skip_defaults=skip_defaults,
        exclude_unset=exclude_unset,
        exclude_defaults=exclude_defaults,
        exclude_none=exclude_none,
    )

    dict_instance = {
        k: self._convert_bytes_to_str(column_name=k, value=v)
        for k, v in dict_instance.items()
    }

    if include and isinstance(include, Set):
        include = translate_list_to_dict(include)
    if exclude and isinstance(exclude, Set):
        exclude = translate_list_to_dict(exclude)

    relation_map = (
        relation_map
        if relation_map is not None
        else translate_list_to_dict(self._iterate_related_models())
    )
    pk_only = getattr(self, "__pk_only__", False)
    if relation_map and not pk_only:
        dict_instance = self._extract_nested_models(
            relation_map=relation_map,
            dict_instance=dict_instance,
            include=include,  # type: ignore
            exclude=exclude,  # type: ignore
            exclude_primary_keys=exclude_primary_keys,
            exclude_through_models=exclude_through_models,
            exclude_list=exclude_list,
        )

    # include model properties as fields in dict
    if object.__getattribute__(self, "Meta").property_fields:
        props = self.get_properties(include=include, exclude=exclude)
        if props:
            dict_instance.update({prop: getattr(self, prop) for prop in props})

    return dict_instance

get_name(lower=True) classmethod

Returns name of the Model class, by default lowercase.

Parameters:

Name Type Description Default
lower bool

flag if name should be set to lowercase

True

Returns:

Type Description
str

name of the model

Source code in ormar\models\newbasemodel.py
451
452
453
454
455
456
457
458
459
460
461
462
463
464
@classmethod
def get_name(cls, lower: bool = True) -> str:
    """
    Returns name of the Model class, by default lowercase.

    :param lower: flag if name should be set to lowercase
    :type lower: bool
    :return: name of the model
    :rtype: str
    """
    name = cls.__name__
    if lower:
        name = name.lower()
    return name

get_properties(include, exclude) classmethod

Returns a set of names of functions/fields decorated with @property_field decorator.

They are added to dictionary when called directly and therefore also are present in fastapi responses.

Parameters:

Name Type Description Default
include Union[Set, Dict, None]

fields to include

required
exclude Union[Set, Dict, None]

fields to exclude

required

Returns:

Type Description
Set[str]

set of property fields names

Source code in ormar\models\newbasemodel.py
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
@classmethod
def get_properties(
    cls, include: Union[Set, Dict, None], exclude: Union[Set, Dict, None]
) -> Set[str]:
    """
    Returns a set of names of functions/fields decorated with
    @property_field decorator.

    They are added to dictionary when called directly and therefore also are
    present in fastapi responses.

    :param include: fields to include
    :type include: Union[Set, Dict, None]
    :param exclude: fields to exclude
    :type exclude: Union[Set, Dict, None]
    :return: set of property fields names
    :rtype: Set[str]
    """

    props = cls.Meta.property_fields
    if include:
        props = {prop for prop in props if prop in include}
    if exclude:
        props = {prop for prop in props if prop not in exclude}
    return props

get_relation_model_id(target_field)

Returns an id of the relation side model to use in prefetch query.

Parameters:

Name Type Description Default
target_field BaseField

field with relation definition

required

Returns:

Type Description
Optional[int]

value of pk if set

Source code in ormar\models\newbasemodel.py
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
def get_relation_model_id(self, target_field: "BaseField") -> Optional[int]:
    """
    Returns an id of the relation side model to use in prefetch query.

    :param target_field: field with relation definition
    :type target_field: "BaseField"
    :return: value of pk if set
    :rtype: Optional[int]
    """
    if target_field.virtual or target_field.is_multi:
        return self.pk
    related_name = target_field.name
    related_model = getattr(self, related_name)
    return None if not related_model else related_model.pk

json(*, include=None, exclude=None, by_alias=False, skip_defaults=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, encoder=None, exclude_primary_keys=False, exclude_through_models=False, **dumps_kwargs)

Generate a JSON representation of the model, include and exclude arguments as per dict().

encoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().

Source code in ormar\models\newbasemodel.py
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
def json(  # type: ignore # noqa A003
    self,
    *,
    include: Union[Set, Dict] = None,
    exclude: Union[Set, Dict] = None,
    by_alias: bool = False,
    skip_defaults: bool = None,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    encoder: Optional[Callable[[Any], Any]] = None,
    exclude_primary_keys: bool = False,
    exclude_through_models: bool = False,
    **dumps_kwargs: Any,
) -> str:
    """
    Generate a JSON representation of the model, `include` and `exclude`
    arguments as per `dict()`.

    `encoder` is an optional function to supply as `default` to json.dumps(),
    other arguments as per `json.dumps()`.
    """
    if skip_defaults is not None:  # pragma: no cover
        warnings.warn(
            f'{self.__class__.__name__}.json(): "skip_defaults" is deprecated '
            f'and replaced by "exclude_unset"',
            DeprecationWarning,
        )
        exclude_unset = skip_defaults
    encoder = cast(Callable[[Any], Any], encoder or self.__json_encoder__)
    data = self.dict(
        include=include,
        exclude=exclude,
        by_alias=by_alias,
        exclude_unset=exclude_unset,
        exclude_defaults=exclude_defaults,
        exclude_none=exclude_none,
        exclude_primary_keys=exclude_primary_keys,
        exclude_through_models=exclude_through_models,
    )
    if self.__custom_root_type__:  # pragma: no cover
        data = data["__root__"]
    return self.__config__.json_dumps(data, default=encoder, **dumps_kwargs)

pk_type() classmethod

Shortcut to models primary key field type

Source code in ormar\models\newbasemodel.py
493
494
495
496
@classmethod
def pk_type(cls) -> Any:
    """Shortcut to models primary key field type"""
    return cls.Meta.model_fields[cls.Meta.pkname].__type__

remove(parent, name)

Removes child from relation with given name in RelationshipManager

Source code in ormar\models\newbasemodel.py
504
505
506
def remove(self, parent: "Model", name: str) -> None:
    """Removes child from relation with given name in RelationshipManager"""
    self._orm.remove_parent(self, parent, name)

set_save_status(status)

Sets value of the save status

Source code in ormar\models\newbasemodel.py
508
509
510
def set_save_status(self, status: bool) -> None:
    """Sets value of the save status"""
    object.__setattr__(self, "_orm_saved", status)

update_forward_refs(**localns) classmethod

Processes fields that are ForwardRef and need to be evaluated into actual models.

Expands relationships, register relation in alias manager and substitutes sqlalchemy columns with new ones with proper column type (null before).

Populates Meta table of the Model which is left empty before.

Sets self_reference flag on models that links to themselves.

Calls the pydantic method to evaluate pydantic fields.

Parameters:

Name Type Description Default
localns Any

local namespace

{}

Returns:

Type Description
None

None

Source code in ormar\models\newbasemodel.py
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
@classmethod
def update_forward_refs(cls, **localns: Any) -> None:
    """
    Processes fields that are ForwardRef and need to be evaluated into actual
    models.

    Expands relationships, register relation in alias manager and substitutes
    sqlalchemy columns with new ones with proper column type (null before).

    Populates Meta table of the Model which is left empty before.

    Sets self_reference flag on models that links to themselves.

    Calls the pydantic method to evaluate pydantic fields.

    :param localns: local namespace
    :type localns: Any
    :return: None
    :rtype: None
    """
    globalns = sys.modules[cls.__module__].__dict__.copy()
    globalns.setdefault(cls.__name__, cls)
    fields_to_check = cls.Meta.model_fields.copy()
    for field in fields_to_check.values():
        if field.has_unresolved_forward_refs():
            field = cast(ForeignKeyField, field)
            field.evaluate_forward_ref(globalns=globalns, localns=localns)
            field.set_self_reference_flag()
            if field.is_multi and not field.through:
                field = cast(ormar.ManyToManyField, field)
                field.create_default_through_model()
            expand_reverse_relationship(model_field=field)
            register_relation_in_alias_manager(field=field)
            update_column_definition(model=cls, field=field)
    populate_meta_sqlalchemy_table_if_required(meta=cls.Meta)
    super().update_forward_refs(**localns)
    cls.Meta.requires_ref_update = False

update_from_dict(value_dict)

Updates self with values of fields passed in the dictionary.

Parameters:

Name Type Description Default
value_dict Dict

dictionary of fields names and values

required

Returns:

Type Description
NewBaseModel

self

Source code in ormar\models\newbasemodel.py
931
932
933
934
935
936
937
938
939
940
941
942
def update_from_dict(self, value_dict: Dict) -> "NewBaseModel":
    """
    Updates self with values of fields passed in the dictionary.

    :param value_dict: dictionary of fields names and values
    :type value_dict: Dict
    :return: self
    :rtype: NewBaseModel
    """
    for key, value in value_dict.items():
        setattr(self, key, value)
    return self