Skip to content

model

Model

Bases: ModelRow

Source code in ormar/models/model.py
Python
 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
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
class Model(ModelRow):
    __abstract__ = False
    if TYPE_CHECKING:  # pragma nocover
        ormar_config: OrmarConfig

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

    async def _execute_query(
        self,
        expr: Executable,
        is_select: bool = False,
        params: Optional[dict] = None,
    ) -> Any:
        """
        Run a statement of this model: fetch one row of a select, otherwise
        execute the write and return its result (inserted primary key or
        number of changed rows).

        Single-row writes and ``load()`` pass a cached statement template
        (see ``ormar.queryset.templates``) and its values as ``params``.

        :param expr: statement to run
        :type expr: Executable
        :param is_select: fetch one row instead of executing a write
        :type is_select: bool
        :param params: values for named bind parameters of the statement
        :type params: Optional[dict]
        :return: fetched row, inserted primary key or row count
        :rtype: Any
        """
        async with self.ormar_config.database.get_query_executor() as executor:
            row = (
                await executor.fetch_one(query=expr, params=params)
                if is_select
                else await executor.execute(query=expr, params=params)
            )
        return row

    async def _emit_signal(self, name: str, **kwargs: Any) -> None:
        """
        Emit a lifecycle signal on this model's SignalEmitter.

        When ``ormar_config.emit_parent_signals`` is True, the same signal is
        also dispatched on every concrete ormar ancestor in the MRO. Each
        emit uses ``sender=ancestor_cls`` so handlers registered with
        ``@pre_save(Parent)`` see the parent class as the sender.

        :param name: signal name on the SignalEmitter (e.g. ``"pre_save"``).
        :type name: str
        :param kwargs: extra payload forwarded to receivers.
        :type kwargs: Any
        """
        cls = type(self)
        await getattr(self.ormar_config.signals, name).send(sender=cls, **kwargs)
        if not self.ormar_config.emit_parent_signals:
            return
        seen = {id(self.ormar_config.signals)}
        for ancestor in cls.__mro__[1:]:
            cfg = getattr(ancestor, "ormar_config", None)
            if cfg is None or cfg.abstract or id(cfg.signals) in seen:
                continue
            seen.add(id(cfg.signals))
            await getattr(cfg.signals, name).send(sender=ancestor, **kwargs)

    async def upsert(self: T, **kwargs: Any) -> T:
        """
        Performs either a save or an update:

        * a model loaded from or already saved to the database is updated,
        * a model without a primary key is inserted,
        * a model never saved but with its key set (uuid default, natural or
          composite key) is looked up first and updated if the row exists,
          inserted otherwise.

        For save kwargs are ignored, used only in update if provided.
        ``__force_save__`` is accepted for backwards compatibility and ignored.

        :param kwargs: list of fields to update
        :type kwargs: Any
        :return: saved Model
        :rtype: Model
        """
        self.verify_writable()
        kwargs.pop("__force_save__", None)
        if self.persisted:
            return await self.update(**kwargs)
        if self.pk is None:
            return await self.save()
        template = row_template(
            statement=RowSelectWrite, model_cls=type(self), pk=self.pk
        )
        row = await self._execute_query(
            expr=template.statement, is_select=True, params=template.params
        )
        if not row:
            return await self.save()
        return await self.update(_partial=False, **kwargs)

    def _verify_key_parts_set(self, row: dict[str, Any]) -> None:
        """
        Checks that every primary key column the database does not generate
        is set before an insert.

        :raises ModelPersistenceError: if a key part is missing
        :param row: values about to be inserted, by column name
        :type row: dict[str, Any]
        """
        key = self.ormar_config.pk
        if key.autoincrement:
            return
        model_fields = self.ormar_config.model_fields
        missing: list[str] = []
        for column in key.column_aliases():
            owners = [
                name
                for name in self.get_field_names_of_column(column=column)
                if name in key.fields
            ]
            if row.get(column) is None and all(
                model_fields[name].server_default is None for name in owners
            ):
                missing.extend(name for name in owners if name not in missing)
        if missing:
            raise ModelPersistenceError(
                f"{self.__class__.__name__} primary key parts must be set before "
                f"saving: {missing}"
            )

    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
        """
        return cast(T, await self._save())

    async def _save(
        self: T, on_conflict: Optional[Literal["ignore"]] = None
    ) -> Optional[T]:
        """
        Body of ``save()``. With ``on_conflict="ignore"`` a row conflicting with
        an existing one is skipped: ``None`` is returned, ``post_save`` not sent.

        :param on_conflict: ``ignore`` to skip a conflicting row
        :type on_conflict: Optional[Literal["ignore"]]
        :return: saved Model, ``None`` when the row was skipped
        :rtype: Optional[Model]
        """
        self.verify_writable()
        await self._emit_signal("pre_save", instance=self)
        self_fields = self._prepare_insert_row()
        key = self.ormar_config.pk
        # MySQL has no conflict clause telling an insert from a skipped row, so
        # it runs a plain insert and a duplicate key error means skipped
        rules = self.ormar_config.database.rules
        returning = bool(on_conflict) and rules.conflict_returning
        template = insert_template(
            model_cls=type(self),
            values=self_fields,
            on_conflict=on_conflict if returning else None,
            returning=key.column_aliases() if returning else (),
        )
        try:
            pk = await self._execute_query(
                expr=template.statement, is_select=returning, params=template.params
            )
        except IntegrityError as error:
            if not on_conflict or not rules.is_duplicate_key(error=error):
                raise
            return None  # pragma: no cover
        if returning:  # pragma: no cover
            if pk is None:
                return None
            pk = key.getter(keys=key.column_aliases())(pk)

        pk_returned_from_insert = False
        if pk and self.pk is None and isinstance(pk, key.python_type()):
            for field, part in key.to_dict(value=pk).items():
                setattr(self, field, part)
            pk_returned_from_insert = True

        if self.pk is None:
            raise ModelPersistenceError(  # pragma: no cover
                f"Could not recover the generated primary key for "
                f"{self.__class__.__name__} after INSERT. This happens on "
                "backends that lack RETURNING support for server-side "
                "defaults on non-AUTO_INCREMENT primary keys — most notably "
                "Oracle MySQL, which does not implement RETURNING in any "
                "version. Use autoincrement=True, provide the primary key "
                "client-side, or switch to a RETURNING-capable backend "
                "(PostgreSQL, SQLite 3.35+, MariaDB 10.5+)."
            )

        self.set_save_status(True)
        # refresh server-side defaults — but skip the pk if the insert already
        # returned it, so save() stays a single round-trip when the pk is the
        # only server_default field.
        if any(
            field.server_default is not None
            for name, field in self.ormar_config.model_fields.items()
            if name not in self_fields
            and not (pk_returned_from_insert and name in key.fields)
        ):
            await self.load()

        self._reset_change_tracking()
        await self._emit_signal("post_save", instance=self)
        return self

    def _prepare_insert_row(self) -> builtins.dict[str, Any]:
        """
        Fill the default values of the instance and return its row to insert,
        by column name. A generated primary key that is not set is left out.

        :raises ModelPersistenceError: if only a part of the primary key is set
        :return: inserted values by column name
        :rtype: dict[str, Any]
        """
        self_fields = self._extract_model_db_fields()
        key = self.ormar_config.pk
        if not self.pk and key.autoincrement:
            for field in key.fields:
                self_fields.pop(field, None)
        self_fields = self.populate_default_values(self_fields)
        # Values taken from ``__dict__`` are already set, re-assigning them only
        # costs a validation and two hash recomputations per field.
        current_values = self.__dict__
        related_names = self.extract_related_names()
        self.update_from_dict(
            {
                name: value
                for name, value in self_fields.items()
                if name not in related_names
                and name in self.ormar_config.model_fields
                and (name not in current_values or current_values[name] is not value)
            }
        )
        self_fields = self.translate_columns_to_aliases(self_fields)
        self._verify_key_parts_set(row=self_fields)
        return self_fields

    @classmethod
    def _conflict_updates(
        cls,
        update_fields: Optional[list[str]],
        update_values: Optional[builtins.dict[str, Any]],
    ) -> tuple[builtins.dict[str, Any], builtins.dict[str, Any]]:
        """
        Validate the ``update_values`` of an upsert like ``QuerySet.update()``
        validates its values and return the ``on_update`` values of the fields
        set by neither ``update_fields`` nor ``update_values``, and the
        ``update_values`` as column values or expression nodes, both by column
        name.

        :param update_fields: names of the fields updated from the inserted row
        :type update_fields: Optional[list[str]]
        :param update_values: value or expression by field name
        :type update_values: Optional[dict[str, Any]]
        :raises QueryDefinitionError: for a field not stored in the model's
            table (unknown, reverse or many to many relation), a field also in
            ``update_fields``, an expression setting a relation, reading a
            related model or another field the upsert sets
        :return: ``on_update`` values and ``update_values``, by column name
        :rtype: tuple[dict[str, Any], dict[str, Any]]
        """
        update_fields = update_fields or []
        update_values = update_values or {}
        # foreign keys stored in the model's own table, no reverse or m2m names
        related_names = cls._extract_db_related_names()
        unknown = [
            name
            for name in update_values
            if name not in cls.extract_db_own_fields() and name not in related_names
        ]
        if unknown:
            raise QueryDefinitionError(
                f"update_values names fields the model does not store in its "
                f"table: {unknown}"
            )
        repeated = [name for name in update_values if name in update_fields]
        if repeated:
            raise QueryDefinitionError(
                f"Fields cannot be in both update_fields and update_values: {repeated}"
            )
        model_fields = cls.ormar_config.model_fields
        on_update = {
            cls.get_column_alias(field_name=name): model_fields[name].get_on_update()
            for name in sorted(cls._onupdate_fields)
            if name not in update_fields and name not in update_values
        }
        updated = {*update_fields, *update_values, *cls._onupdate_fields}
        expressions = {
            name: value._node()
            for name, value in update_values.items()
            if isinstance(value, Expression)
        }
        for name, node in expressions.items():
            expression_columns(node=node, model=cls, upsert=True)
            read = [
                leaf._path
                for leaf in expression_leaves(node=node)
                if isinstance(leaf, F)
            ]
            if name in related_names or any(
                field != name and field in updated for field in read
            ):
                raise QueryDefinitionError(
                    f"update_values cannot set '{name}' from an expression reading "
                    f"{read}: expressions set no relations and read no fields set "
                    f"by the same upsert (use Inserted() for the inserted value)."
                )
        values = cls.validate_update_values(
            {
                name: value
                for name, value in update_values.items()
                if name not in expressions
            }
        )
        values = cls.reconvert_str_to_bytes(values)
        return on_update, cls.translate_columns_to_aliases({**values, **expressions})

    async def _upsert(
        self: T,
        conflict_target: Optional[list[str]] = None,
        update_fields: Optional[list[str]] = None,
        update_values: Optional[builtins.dict[str, Any]] = None,
    ) -> T:
        """
        Insert the instance, or update the row it conflicts with on
        ``conflict_target`` (the primary key by default), in one statement, and
        fill the instance with the stored row. ``update_fields`` (by default
        all inserted fields but the target and the key, none with
        ``update_values``), ``update_values`` and the fields with ``on_update``
        are updated.

        PostgreSQL and SQLite return the stored row from the insert. MySQL has
        no RETURNING and conflicts on any unique key: the row is read back by
        the ``conflict_target`` values.

        Sends pre_save and post_save signals, whether the row was inserted or
        updated.

        :param conflict_target: names of the fields of the conflicting unique key
        :type conflict_target: Optional[list[str]]
        :param update_fields: names of the fields updated on conflict
        :type update_fields: Optional[list[str]]
        :param update_values: values or expressions set on conflict, by field
        :type update_values: Optional[dict[str, Any]]
        :raises QueryDefinitionError: if a field of the target has no value or
            ``update_values`` are invalid (see ``_conflict_updates``)
        :raises NoMatch: if on MySQL no row matches the target values after the
            write (a conflict on another unique key, or values the database
            stores rounded)
        :return: the stored row
        :rtype: Model
        """
        self.verify_writable()
        on_update, values = self._conflict_updates(
            update_fields=update_fields, update_values=update_values
        )
        await self._emit_signal("pre_save", instance=self)
        self_fields = self._prepare_insert_row()
        config = self.ormar_config
        target_fields = conflict_target or list(config.pk.fields)
        unknown = [name for name in target_fields if name not in config.model_fields]
        if unknown:
            raise QueryDefinitionError(
                f"conflict_target names fields the model does not have: {unknown}"
            )
        target = {
            column: self_fields.get(column)
            for field_name in target_fields
            for column in self.get_column_aliases(field_name=field_name)
        }
        missing = [column for column, value in target.items() if value is None]
        if missing:
            raise QueryDefinitionError(
                f"on_conflict='update' needs a value for every field of the "
                f"conflict target, missing: {missing}"
            )
        rules = config.database.rules
        template = insert_template(
            model_cls=type(self),
            values=self_fields,
            on_conflict="update",
            conflict_target=conflict_target,
            update_fields=update_fields,
            on_update=tuple(sorted(on_update)),
            update_values=values,
            returning=(
                tuple(column.name for column in config.table.columns)
                if rules.conflict_returning
                else ()
            ),
        )
        params = {
            **template.params,
            **{
                f"ormar_on_update_{column}": value
                for column, value in on_update.items()
            },
            **update_values_params(update_values=values),
        }
        # each branch runs on its own databases only
        if rules.conflict_returning:  # pragma: no cover
            row = await self._execute_query(
                expr=template.statement, is_select=True, params=params
            )
        else:  # pragma: no cover
            await self._execute_query(expr=template.statement, params=params)
            table = config.table
            row = await self._execute_query(
                expr=sqlalchemy.select(table).where(
                    *(table.c[column] == value for column, value in target.items())
                ),
                is_select=True,
            )
            if row is None:
                raise NoMatch(
                    f"The row was written, but no row matches the conflict target "
                    f"{target} when read back: the conflict was on another unique "
                    f"key, or the database stored different values (rounded "
                    f"floats or datetimes)"
                )
        self.update_from_dict(self.translate_row_to_fields(row=dict(row)))
        self.set_save_status(True)
        self._reset_change_tracking()
        await self._emit_signal("post_save", instance=self)
        return self

    async def save_related(  # noqa: CCR001, CFQ002
        self,
        follow: bool = False,
        save_all: bool = False,
        relation_map: Optional[builtins.dict] = None,
        exclude: Union[set, builtins.dict, None] = None,
        update_count: int = 0,
        previous_model: Optional["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
        """
        self.verify_writable()
        relation_map = (
            relation_map
            if relation_map is not None
            else cast(builtins.dict, self._default_relation_map())
        )
        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: Optional[list[str]] = None,
        _partial: Optional[bool] = None,
        **kwargs: Any,
    ) -> T:
        """
        Performs update of Model instance in the database.
        Fields can be updated before or you can pass them as kwargs.

        Which columns are written:

        * ``_columns`` given: only those (and ``onupdate`` fields),
        * nothing changed since the model was loaded or saved: all columns,
        * partial update (``_partial=True``, or ``partial_updates=True`` in
          ``OrmarConfig`` when ``_partial`` is not given): the kwargs, the
          fields assigned since the last load or save (also by ``pre_update``
          signal handlers), json fields mutated in place (with
          ``partial_updates=True``) and ``onupdate`` fields,
        * otherwise all columns. With the default ``partial_updates=None`` a
          ``DeprecationWarning`` is emitted when kwargs are passed and other
          columns are written too, as the default changes in a future
          release.

        Sends pre_update and post_update signals.

        Sets model save status to True.

        :param _columns: list of columns to update
        :type _columns: Optional[list[str]]
        :param _partial: write only changed fields (``True``) or all columns
            (``False``), ``None`` follows ``partial_updates`` of the config
        :type _partial: Optional[bool]
        :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
        """
        self.verify_writable()
        explicit_fields = self.__setattr_fields__ | kwargs.keys()
        auto_onupdate = self._onupdate_fields - explicit_fields
        values = self.populate_onupdate_value(
            dict(kwargs), explicit_fields=explicit_fields
        )
        if values:
            self.update_from_dict(values)

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

        await self._emit_signal("pre_update", instance=self, passed_args=kwargs)
        self_fields = self._extract_model_db_fields()
        key_fields = {
            value_key
            for field in self.ormar_config.pk.fields
            for value_key in self.value_keys(field_name=field)
        }
        key_moved = self.persisted_key != self.pk
        if not key_moved:
            for field in key_fields:
                self_fields.pop(field, None)
        self_fields = self._fields_to_update(
            self_fields=self_fields,
            columns=_columns,
            partial=_partial,
            changed=self._changed_fields() - auto_onupdate,
            passed_kwargs=bool(kwargs),
            key_fields=key_fields if key_moved else set(),
        )
        if self_fields:
            self_fields = self.translate_columns_to_aliases(self_fields)
            template = row_template(
                statement=UpdateWrite,
                model_cls=type(self),
                values=self_fields,
                pk=self.persisted_key,
            )
            await self._execute_query(expr=template.statement, params=template.params)
        self.set_save_status(True)
        self._reset_change_tracking()
        await self._emit_signal("post_update", instance=self)
        return self

    def _fields_to_update(  # noqa: CFQ002
        self,
        self_fields: builtins.dict[str, Any],
        columns: Optional[list[str]],
        partial: Optional[bool],
        changed: set[str],
        passed_kwargs: bool,
        key_fields: set[str],
    ) -> builtins.dict[str, Any]:
        """
        Selects the column values ``update()`` writes, see its docstring.

        :param self_fields: values of all columns of the model by field name
        :type self_fields: dict[str, Any]
        :param columns: ``_columns`` passed to ``update()``
        :type columns: Optional[list[str]]
        :param partial: ``_partial`` passed to ``update()``
        :type partial: Optional[bool]
        :param changed: fields changed since the last load or save
        :type changed: set[str]
        :param passed_kwargs: if ``update()`` received field values
        :type passed_kwargs: bool
        :param key_fields: primary key fields to write as the key moved
        :type key_fields: set[str]
        :return: values of the columns to write
        :rtype: dict[str, Any]
        """
        if columns:
            return self._select_update_columns(
                self_fields=self_fields, field_names=set(columns) | key_fields
            )
        if partial is None:
            partial = self.ormar_config.partial_updates
        if not changed or partial is False:
            return self_fields
        selected = self._select_update_columns(
            self_fields=self_fields, field_names=changed | key_fields
        )
        if partial:
            return selected
        if passed_kwargs and selected.keys() != self_fields.keys():
            warnings.warn(
                f"{self.get_name(lower=False)}.update(**kwargs) writes all columns "
                "of the row, not only the passed and changed fields, which reverts "
                "changes made in the database since the model was loaded. Set "
                "`partial_updates=True` in `OrmarConfig` to write only the changed "
                "fields (the default in a future release), `partial_updates=False` "
                "to keep writing all columns, or pass `_columns`.",
                DeprecationWarning,
                stacklevel=3,
            )
        return self_fields

    def _select_update_columns(
        self, self_fields: builtins.dict[str, Any], field_names: set[str]
    ) -> builtins.dict[str, Any]:
        """
        Keeps the values of the given fields (by field or column name; a foreign
        key stored in several columns keeps all of them, a column it shares
        with other fields under the key that column is kept under, see
        ``value_keys``) and of ``onupdate`` fields.

        :param self_fields: values of the model columns by field name
        :type self_fields: dict[str, Any]
        :param field_names: names of fields to keep
        :type field_names: set[str]
        :return: values of the selected columns
        :rtype: dict[str, Any]
        """
        model_fields = self.ormar_config.model_fields
        selected = set(field_names) | self._onupdate_fields
        for name in field_names:
            selected.update(self.get_column_aliases(field_name=name))
            field = model_fields.get(name)
            if field is not None and field.kind.holds_columns:
                selected.update(self.value_keys(field_name=name))
        return {k: v for k, v in self_fields.items() if k in selected}

    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
        """
        self.verify_writable()
        await self._emit_signal("pre_delete", instance=self)
        template = row_template(
            statement=DeleteWrite, model_cls=type(self), pk=self.persisted_key
        )
        result = await self._execute_query(
            expr=template.statement, params=template.params
        )
        self.set_save_status(False)
        self.set_persisted(persisted=False)
        await self._emit_signal("post_delete", instance=self)
        return result

    async def _load_by_set_fields(self) -> dict[str, Any]:
        """
        Load the row of a key-only model referenced by a unique non-pk field
        (``ForeignKey(to_field=...)``): it has no primary key, so the row is
        looked up by its set own fields.

        :raises NoMatch: if no row matches
        :return: values of the row by field name
        :rtype: dict[str, Any]
        """
        own_fields = self.extract_db_own_fields()
        lookup = {
            name: value
            for name, value in self.__dict__.items()
            if name in own_fields and value is not None
        }
        found = await type(self).objects.get(**lookup)
        return {name: found.__dict__[name] for name in own_fields}

    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
        """
        if self.persisted_key is None and self.__pk_only__:
            kwargs = await self._load_by_set_fields()
        elif self.persisted_key is None:
            raise NoMatch(
                f"{self.get_name(lower=False)} has no primary key, it cannot be "
                "loaded from the database"
            )
        else:
            template = row_template(
                statement=RowSelectWrite, model_cls=type(self), pk=self.persisted_key
            )
            row = await self._execute_query(
                expr=template.statement, is_select=True, params=template.params
            )
            if not row:  # pragma nocover
                raise NoMatch(
                    "Instance was deleted from database and cannot be refreshed"
                )
            kwargs = self.translate_row_to_fields(row=dict(row))
        self.update_from_dict(kwargs)
        self.set_save_status(True)
        self._reset_change_tracking()
        return self

    async def load_all(
        self: T,
        follow: bool = False,
        exclude: Union[list, str, set, dict, None] = None,
        order_by: Union[list, str, None] = None,
        max_depth: Optional[int] = None,
        follow_reverse: Union[bool, int] = 0,
    ) -> 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 max_depth: number of relations to follow at most with
            follow=True, forward foreign keys ``DEFAULT_FOLLOW_DEPTH`` (5) deep by
            default (every relation without limit in the deprecated ``map``
            traversal)
        :type max_depth: Optional[int]
        :param follow_reverse: number of first levels where follow=True also
            follows reverse and many to many relations, ``True`` = 1
        :type follow_reverse: Union[bool, int]
        :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._follow_relation_paths(
                max_depth=max_depth, follow_reverse=follow_reverse
            )
        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.persisted_key)
        self._orm.clear()
        self.update_from_dict(instance.model_dump())
        self._reset_change_tracking()
        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
Python
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
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
    """
    self.verify_writable()
    await self._emit_signal("pre_delete", instance=self)
    template = row_template(
        statement=DeleteWrite, model_cls=type(self), pk=self.persisted_key
    )
    result = await self._execute_query(
        expr=template.statement, params=template.params
    )
    self.set_save_status(False)
    self.set_persisted(persisted=False)
    await self._emit_signal("post_delete", 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
Python
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
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
    """
    if self.persisted_key is None and self.__pk_only__:
        kwargs = await self._load_by_set_fields()
    elif self.persisted_key is None:
        raise NoMatch(
            f"{self.get_name(lower=False)} has no primary key, it cannot be "
            "loaded from the database"
        )
    else:
        template = row_template(
            statement=RowSelectWrite, model_cls=type(self), pk=self.persisted_key
        )
        row = await self._execute_query(
            expr=template.statement, is_select=True, params=template.params
        )
        if not row:  # pragma nocover
            raise NoMatch(
                "Instance was deleted from database and cannot be refreshed"
            )
        kwargs = self.translate_row_to_fields(row=dict(row))
    self.update_from_dict(kwargs)
    self.set_save_status(True)
    self._reset_change_tracking()
    return self

load_all(follow=False, exclude=None, order_by=None, max_depth=None, follow_reverse=0) 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
max_depth Optional[int]

number of relations to follow at most with follow=True, forward foreign keys DEFAULT_FOLLOW_DEPTH (5) deep by default (every relation without limit in the deprecated map traversal)

None
follow_reverse Union[bool, int]

number of first levels where follow=True also follows reverse and many to many relations, True = 1

0
order_by Union[list, str, None]

columns by which models should be sorted

None
exclude Union[list, str, set, dict, None]

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
Python
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
async def load_all(
    self: T,
    follow: bool = False,
    exclude: Union[list, str, set, dict, None] = None,
    order_by: Union[list, str, None] = None,
    max_depth: Optional[int] = None,
    follow_reverse: Union[bool, int] = 0,
) -> 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 max_depth: number of relations to follow at most with
        follow=True, forward foreign keys ``DEFAULT_FOLLOW_DEPTH`` (5) deep by
        default (every relation without limit in the deprecated ``map``
        traversal)
    :type max_depth: Optional[int]
    :param follow_reverse: number of first levels where follow=True also
        follows reverse and many to many relations, ``True`` = 1
    :type follow_reverse: Union[bool, int]
    :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._follow_relation_paths(
            max_depth=max_depth, follow_reverse=follow_reverse
        )
    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.persisted_key)
    self._orm.clear()
    self.update_from_dict(instance.model_dump())
    self._reset_change_tracking()
    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
Python
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
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
    """
    return cast(T, await self._save())

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 Optional[Model]

previous model from which method came

None
exclude Union[set, dict, None]

items to exclude during saving of relations

None
relation_map Optional[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
Python
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
async def save_related(  # noqa: CCR001, CFQ002
    self,
    follow: bool = False,
    save_all: bool = False,
    relation_map: Optional[builtins.dict] = None,
    exclude: Union[set, builtins.dict, None] = None,
    update_count: int = 0,
    previous_model: Optional["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
    """
    self.verify_writable()
    relation_map = (
        relation_map
        if relation_map is not None
        else cast(builtins.dict, self._default_relation_map())
    )
    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, _partial=None, **kwargs) async

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

Which columns are written:

  • _columns given: only those (and onupdate fields),
  • nothing changed since the model was loaded or saved: all columns,
  • partial update (_partial=True, or partial_updates=True in OrmarConfig when _partial is not given): the kwargs, the fields assigned since the last load or save (also by pre_update signal handlers), json fields mutated in place (with partial_updates=True) and onupdate fields,
  • otherwise all columns. With the default partial_updates=None a DeprecationWarning is emitted when kwargs are passed and other columns are written too, as the default changes in a future release.

Sends pre_update and post_update signals.

Sets model save status to True.

Parameters:

Name Type Description Default
_columns Optional[list[str]]

list of columns to update

None
_partial Optional[bool]

write only changed fields (True) or all columns (False), None follows partial_updates of the config

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
Python
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
async def update(
    self: T,
    _columns: Optional[list[str]] = None,
    _partial: Optional[bool] = None,
    **kwargs: Any,
) -> T:
    """
    Performs update of Model instance in the database.
    Fields can be updated before or you can pass them as kwargs.

    Which columns are written:

    * ``_columns`` given: only those (and ``onupdate`` fields),
    * nothing changed since the model was loaded or saved: all columns,
    * partial update (``_partial=True``, or ``partial_updates=True`` in
      ``OrmarConfig`` when ``_partial`` is not given): the kwargs, the
      fields assigned since the last load or save (also by ``pre_update``
      signal handlers), json fields mutated in place (with
      ``partial_updates=True``) and ``onupdate`` fields,
    * otherwise all columns. With the default ``partial_updates=None`` a
      ``DeprecationWarning`` is emitted when kwargs are passed and other
      columns are written too, as the default changes in a future
      release.

    Sends pre_update and post_update signals.

    Sets model save status to True.

    :param _columns: list of columns to update
    :type _columns: Optional[list[str]]
    :param _partial: write only changed fields (``True``) or all columns
        (``False``), ``None`` follows ``partial_updates`` of the config
    :type _partial: Optional[bool]
    :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
    """
    self.verify_writable()
    explicit_fields = self.__setattr_fields__ | kwargs.keys()
    auto_onupdate = self._onupdate_fields - explicit_fields
    values = self.populate_onupdate_value(
        dict(kwargs), explicit_fields=explicit_fields
    )
    if values:
        self.update_from_dict(values)

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

    await self._emit_signal("pre_update", instance=self, passed_args=kwargs)
    self_fields = self._extract_model_db_fields()
    key_fields = {
        value_key
        for field in self.ormar_config.pk.fields
        for value_key in self.value_keys(field_name=field)
    }
    key_moved = self.persisted_key != self.pk
    if not key_moved:
        for field in key_fields:
            self_fields.pop(field, None)
    self_fields = self._fields_to_update(
        self_fields=self_fields,
        columns=_columns,
        partial=_partial,
        changed=self._changed_fields() - auto_onupdate,
        passed_kwargs=bool(kwargs),
        key_fields=key_fields if key_moved else set(),
    )
    if self_fields:
        self_fields = self.translate_columns_to_aliases(self_fields)
        template = row_template(
            statement=UpdateWrite,
            model_cls=type(self),
            values=self_fields,
            pk=self.persisted_key,
        )
        await self._execute_query(expr=template.statement, params=template.params)
    self.set_save_status(True)
    self._reset_change_tracking()
    await self._emit_signal("post_update", instance=self)
    return self

upsert(**kwargs) async

Performs either a save or an update:

  • a model loaded from or already saved to the database is updated,
  • a model without a primary key is inserted,
  • a model never saved but with its key set (uuid default, natural or composite key) is looked up first and updated if the row exists, inserted otherwise.

For save kwargs are ignored, used only in update if provided. __force_save__ is accepted for backwards compatibility and ignored.

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
Python
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
async def upsert(self: T, **kwargs: Any) -> T:
    """
    Performs either a save or an update:

    * a model loaded from or already saved to the database is updated,
    * a model without a primary key is inserted,
    * a model never saved but with its key set (uuid default, natural or
      composite key) is looked up first and updated if the row exists,
      inserted otherwise.

    For save kwargs are ignored, used only in update if provided.
    ``__force_save__`` is accepted for backwards compatibility and ignored.

    :param kwargs: list of fields to update
    :type kwargs: Any
    :return: saved Model
    :rtype: Model
    """
    self.verify_writable()
    kwargs.pop("__force_save__", None)
    if self.persisted:
        return await self.update(**kwargs)
    if self.pk is None:
        return await self.save()
    template = row_template(
        statement=RowSelectWrite, model_cls=type(self), pk=self.pk
    )
    row = await self._execute_query(
        expr=template.statement, is_select=True, params=template.params
    )
    if not row:
        return await self.save()
    return await self.update(_partial=False, **kwargs)