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
Python
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
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()
        self._flatten_paths: set[PathParts] = set()
        self._flatten_map_cache: Optional[FlattenMap] = None
        self._included_relation_paths: set[PathParts] = set()

    @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()
        new_excludable._flatten_paths = set(other._flatten_paths)
        new_excludable._included_relation_paths = set(other._included_relation_paths)
        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 included_relation_paths(self) -> set[str]:
        """
        Returns the relation paths that fields included with ``fields()``
        are nested in, e.g. ``{"category__created_by"}`` for
        ``fields(["category__created_by__name"])``.

        :return: dunder relation paths of the included nested fields
        :rtype: set[str]
        """
        return {"__".join(path_parts) for path_parts in self._included_relation_paths}

    def flatten_map(self) -> Optional[FlattenMap]:
        """
        Return a :class:`FlattenMap` over the stored flatten paths, built
        lazily on first call and cached for reuse. The cache is invalidated
        whenever ``_set_slot`` adds a new flatten path. Returns ``None`` when
        no flatten paths are stored, so callers can short-circuit.

        :return: FlattenMap wrapping the nested-Ellipsis dict, or ``None``
            when no flatten paths are stored
        :rtype: Optional[FlattenMap]
        """
        if not self._flatten_paths:
            return None
        if self._flatten_map_cache is None:
            self._flatten_map_cache = FlattenMap(
                data=build_flatten_map(self._flatten_paths)
            )
        return self._flatten_map_cache

    @staticmethod
    def _make_key(model_cls: type["Model"], alias: str = "") -> str:
        """
        Build the items-dict key for ``(alias, model)``. Centralized so
        every call site shares one definition of "which Excludable is
        this".
        """
        prefix = f"{alias}_" if alias else ""
        return f"{prefix}{model_cls.get_name(lower=True)}"

    @staticmethod
    def _resolve_path(
        source_model: type["Model"],
        parts_prefix: tuple,
    ) -> tuple[str, type["Model"]]:
        """
        Resolve a dunder path prefix to its target ``(alias, model)``.

        An empty prefix returns ``("", source_model)``. Goes through
        :func:`get_relationship_alias_model_and_str`, which mutates its
        ``related_parts`` argument while resolving through models - the
        prefix tuple is copied to a list to insulate the caller.

        Examples (aliases are ``alias_for`` hashes of the path, shown here
        as ``<...>``)::

            _resolve_path(Post, ())
            # => ("", Post)

            _resolve_path(Post, ("category",))
            # => ("<alias_for('category')>", Category)

            _resolve_path(Role, ("users", "categories"))
            # => ("<alias_for('users__categories')>", Category)

        :param source_model: model from which the path is rooted
        :type source_model: type[Model]
        :param parts_prefix: pre-split path segments
        :type parts_prefix: tuple
        :return: alias and target model at the prefix
        :rtype: tuple[str, type[Model]]
        """
        if not parts_prefix:
            return "", source_model
        alias, model, _, _ = get_relationship_alias_model_and_str(
            source_model=source_model,
            related_parts=list(parts_prefix),
        )
        return alias, model

    def _referenced_at(
        self,
        source_model: type["Model"],
        parts_prefix: tuple,
    ) -> bool:
        """
        Return whether this :class:`ExcludableItems` already carries any
        include or exclude entry for the model at ``parts_prefix``.

        Used by :meth:`with_projection_exclusions` to detect whether the
        user's ``fields()`` call referenced a given path - an empty
        ``Excludable`` (or none at all) means "not referenced".

        Examples, contrasting the same path under two different
        ``fields()`` specs::

            # Built from Post.objects.fields(["name"])
            #   items = {"post": Excludable(include={"name"})}

            excludable._referenced_at(Post, ())
            # => True   (Post has a non-empty include)

            excludable._referenced_at(Post, ("category",))
            # => False  (no entry for Category)


            # Built from Post.objects.fields(["name", "category__name"])
            #   items = {
            #       "post": Excludable(include={"name"}),
            #       "<alias>_category": Excludable(include={"name"}),
            #   }

            excludable._referenced_at(Post, ("category",))
            # => True   (Category has a non-empty include)

        :param source_model: model from which the path is rooted
        :type source_model: type[Model]
        :param parts_prefix: pre-split path segments to check
        :type parts_prefix: tuple
        :return: True if a non-empty entry exists at the prefix
        :rtype: bool
        """
        alias, model = self._resolve_path(source_model, parts_prefix)
        exc = self.items.get(self._make_key(model, alias))
        return exc is not None and bool(exc.include or exc.exclude)

    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 = self._make_key(model_cls, alias)
        excludable = self.items.get(key)
        if not excludable:
            excludable = Excludable()
            self.items[key] = excludable
        return excludable

    def with_entry_alias(
        self, model_cls: type["Model"], source_alias: str, target_alias: str
    ) -> "ExcludableItems":
        """
        Returns a copy in which the entry of a model stored under one alias is also
        stored under another one. Used when a model is queried from a different root
        than the one the include/exclude paths were defined from (prefetch queries).

        :param model_cls: model which entry should be re-aliased
        :type model_cls: type[Model]
        :param source_alias: alias the entry is stored under
        :type source_alias: str
        :param target_alias: alias the entry should be available under
        :type target_alias: str
        :return: copy of excludable items with the re-aliased entry
        :rtype: ExcludableItems
        """
        new_excludable = ExcludableItems.from_excludable(self)
        source = self.items.get(self._make_key(model_cls, source_alias))
        new_excludable.items[self._make_key(model_cls, target_alias)] = (
            source.get_copy() if source else Excludable()
        )
        return new_excludable

    def build(
        self,
        items: Union[list[str], str, tuple[str], set[str], dict],
        model_cls: type["Model"],
        slot: Slot = "include",
    ) -> 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 three sets of values - include, exclude, and flatten.

        :param items: values to be included, excluded or flattened
        :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 slot: which slot to write parsed values into
        :type slot: Slot
        """
        if isinstance(items, str):
            items = {items}

        if isinstance(items, dict):
            self._traverse_dict(
                values=items,
                source_model=model_cls,
                model_cls=model_cls,
                slot=slot,
            )
        else:
            items = set(items)
            nested_items = set(x for x in items if "__" in x)
            items.difference_update(nested_items)
            if items:
                self._set_slot(
                    items=items,
                    model_cls=model_cls,
                    slot=slot,
                )
            if nested_items:
                self._traverse_list(values=nested_items, model_cls=model_cls, slot=slot)

        if slot == "flatten":
            self._validate_flatten_prefix_collisions()

    def _set_slot(
        self,
        items: set,
        model_cls: type["Model"],
        slot: Slot,
        alias: str = "",
        path_parts: PathParts = (),
    ) -> None:
        """
        Sets set of values to be stored for the given slot on the key that
        corresponds to the passed model + alias.

        :param items: items to write
        :type items: set
        :param model_cls: target model on which the items are stored
        :type model_cls: type[Model]
        :param slot: which slot to write to
        :type slot: Slot
        :param alias: table alias from relation manager
        :type alias: str
        :param path_parts: tuple of dunder path segments leading to this model
        :type path_parts: PathParts
        """
        if slot == "flatten":
            self._validate_flatten_leaves(
                items=items, model_cls=model_cls, path_parts=path_parts
            )
            for item in items:
                self._flatten_paths.add(path_parts + (item,))
            self._flatten_map_cache = None
        elif slot == "include" and path_parts:
            self._included_relation_paths.add(path_parts)

        key = self._make_key(model_cls, alias)
        excludable = self.items.setdefault(key, Excludable())
        excludable.set_values(value=items, slot=slot)

    def _traverse_dict(  # noqa: CFQ002
        self,
        values: dict,
        source_model: type["Model"],
        model_cls: type["Model"],
        slot: Slot,
        path_parts: PathParts = (),
        alias: str = "",
    ) -> None:
        """
        Goes through dict of nested values and construct/update Excludables.

        :param values: items to include/exclude/flatten
        :type values: dict
        :param source_model: source model from which relations are constructed
        :type source_model: ormar.models.metaclass.ModelMetaclass
        :param model_cls: model reached via ``path_parts``
        :type model_cls: ormar.models.metaclass.ModelMetaclass
        :param slot: which slot to write into
        :type slot: Slot
        :param path_parts: tuple of dunder path segments leading to ``model_cls``
        :type path_parts: PathParts
        :param alias: alias of relation
        :type alias: str
        """
        self_fields = set()
        for key, value in values.items():
            if value is ...:
                self_fields.add(key)
            elif isinstance(value, set):
                nested_parts = path_parts + (key,)
                table_prefix, target_model, _, _ = get_relationship_alias_model_and_str(
                    source_model=source_model,
                    related_parts=list(nested_parts),
                )
                self._set_slot(
                    items=value,
                    model_cls=target_model,
                    slot=slot,
                    alias=table_prefix,
                    path_parts=nested_parts,
                )
            else:
                nested_parts = path_parts + (key,)
                table_prefix, target_model, _, _ = get_relationship_alias_model_and_str(
                    source_model=source_model,
                    related_parts=list(nested_parts),
                )
                self._traverse_dict(
                    values=value,
                    source_model=source_model,
                    model_cls=target_model,
                    slot=slot,
                    path_parts=nested_parts,
                    alias=table_prefix,
                )
        if self_fields:
            self._set_slot(
                items=self_fields,
                model_cls=model_cls,
                slot=slot,
                alias=alias,
                path_parts=path_parts,
            )

    def _traverse_list(
        self, values: set[str], model_cls: type["Model"], slot: Slot
    ) -> None:
        """
        Consume a set of dunder-style paths (``"a__b__c"``) and write each leaf
        to the Excludable for its target model/alias. Each path is split once
        into a tuple and threaded through ``_set_slot`` — no further string
        joins happen downstream.

        :param values: set of dunder-style path strings
        :type values: set[str]
        :param model_cls: source model from which relations are resolved
        :type model_cls: type[Model]
        :param slot: which slot to write into
        :type slot: Slot
        """
        for dunder_path in values:
            parts = tuple(dunder_path.split("__"))
            table_prefix, target_model, _, _ = get_relationship_alias_model_and_str(
                source_model=model_cls,
                related_parts=list(parts[:-1]),
            )
            self._set_slot(
                items={parts[-1]},
                model_cls=target_model,
                slot=slot,
                alias=table_prefix,
                path_parts=parts[:-1],
            )

    @staticmethod
    def _validate_flatten_leaves(
        items: set, model_cls: type["Model"], path_parts: PathParts
    ) -> None:
        """
        Ensure every leaf addressed by a flatten spec is a real relation on the
        target model (not a scalar column and not a through model).

        :param items: set of leaf names being flattened on ``model_cls``
        :type items: set
        :param model_cls: target model on which leaves must resolve to relations
        :type model_cls: type[Model]
        :param path_parts: tuple of segments leading to ``model_cls`` (only
            joined for error messages, never parsed)
        :type path_parts: PathParts
        """
        model_fields = model_cls.ormar_config.model_fields
        for item in items:
            related_field = model_fields.get(item)
            if related_field is None:
                raise QueryDefinitionError(
                    f"Unknown relation '{item}' on model "
                    f"{model_cls.get_name(lower=False)} in flatten_fields path "
                    f"'{join_path(path_parts, item)}'."
                )
            if getattr(related_field, "is_through", False):
                raise QueryDefinitionError(
                    f"Cannot flatten through model '{item}' at path "
                    f"'{join_path(path_parts, item)}'. Flatten the many-to-many "
                    f"relation itself instead."
                )
            if not getattr(related_field, "is_relation", False):
                raise QueryDefinitionError(
                    f"flatten_fields target '{join_path(path_parts, item)}' is "
                    f"not a relation on model {model_cls.get_name(lower=False)}. "
                    f"Only foreign keys, many-to-many, and reverse relations can "
                    f"be flattened."
                )

    def _validate_flatten_prefix_collisions(self) -> None:
        """
        Ensure no flatten path is a strict ancestor of another. Flattening a
        relation replaces it with a scalar PK, so a deeper flatten through the
        same chain is unreachable.

        Works directly on tuple paths — sorted so each prefix's descendants
        follow it immediately, enabling an early break once the prefix no
        longer matches.

        :raises QueryDefinitionError: on any prefix collision
        """
        paths = sorted(self._flatten_paths)
        for i, short in enumerate(paths):
            short_len = len(short)
            for longer in paths[i + 1 :]:
                if longer[:short_len] != short:
                    break
                raise QueryDefinitionError(
                    f"Conflicting flatten directives: "
                    f"'{join_path(short)}' is flattened to its primary key, "
                    f"so nested flatten '{join_path(longer)}' is unreachable."
                )

    def with_projection_exclusions(
        self,
        source_model: type["Model"],
        select_related: list[str],
    ) -> "ExcludableItems":
        """
        Return a copy with relations not referenced by ``fields()`` removed
        from a flat values projection.

        A filter like ``filter(project__id=...)`` auto-joins ``project``;
        without this, a flat ``values()`` call leaks every Project column
        even though only one main-model field was requested. Returns the
        original instance unchanged when ``fields()`` was never called -
        the leak is a values-projection problem, not an ORM-load problem.

        :param source_model: model from which relation paths are rooted
        :type source_model: type[Model]
        :param select_related: paths joined into the query (dunder strings)
        :type select_related: list[str]
        :return: new :class:`ExcludableItems` with implicit excludes added,
            or ``self`` when no ``fields()`` call had any effect
        :rtype: ExcludableItems
        """
        if self.include_entry_count() == 0:
            return self

        excludable = ExcludableItems.from_excludable(self)

        # If fields() never names the source model, project only its PK.
        if not excludable._referenced_at(source_model, ()):
            excludable.get(source_model).pk_only = True

        for path in select_related:
            parts = tuple(path.split("__"))
            # Snapshot which prefixes carry a fields() reference before any
            # exclusions are added below - the exclude additions would
            # otherwise show up as "referenced" on the next iteration.
            referenced = [
                excludable._referenced_at(source_model, parts[: d + 1])
                for d in range(len(parts))
            ]
            # Walk deepest-first so kept_deeper accumulates inward. Each
            # segment still needs its own exclude when not kept, because
            # values_column_map only consults the immediate parent.
            kept_deeper = False
            for i in reversed(range(len(parts))):
                kept_deeper = kept_deeper or referenced[i]
                segment = parts[i]
                parent_alias, parent_model = excludable._resolve_path(
                    source_model, parts[:i]
                )
                parent_exc = excludable.get(parent_model, alias=parent_alias)
                if parent_exc.is_explicitly_included(segment):
                    continue
                if kept_deeper:
                    # Intermediate relation: keep the join but project
                    # PK-only when this segment was never explicitly named.
                    if not referenced[i]:
                        target_alias, target_model = excludable._resolve_path(
                            source_model, parts[: i + 1]
                        )
                        excludable.get(target_model, alias=target_alias).pk_only = True
                    continue
                field = parent_model.ormar_config.model_fields[segment]
                parent_exc.exclude.add(segment)
                if field.is_multi:
                    parent_exc.exclude.add(field.through.get_name())

        return excludable

    def validate_flatten_vs_excludable(self, source_model: type["Model"]) -> None:
        """
        Ensure no flattened relation has sub-field include/exclude on its target.
        Whole-relation include/exclude at the parent level is allowed; only
        sub-field selection on the flattened child is flagged.

        :param source_model: model from which flatten paths are rooted
        :type source_model: type[Model]
        :raises QueryDefinitionError: when a flattened relation has sub-field
            include/exclude on its target model
        """
        for parts in self._flatten_paths:
            table_prefix, target_model, _, _ = get_relationship_alias_model_and_str(
                source_model=source_model,
                related_parts=list(parts),
            )
            child = self.items.get(self._make_key(target_model, table_prefix))
            if not child:
                continue
            conflicts = (child.include | child.exclude) - {...}
            if conflicts:
                raise QueryDefinitionError(
                    f"Flatten conflict: relation '{join_path(parts)}' is "
                    f"flattened but include/exclude specifies children "
                    f"{sorted(conflicts)}. A flattened relation renders only "
                    f"its primary key and cannot have children selected."
                )

build(items, model_cls, slot='include')

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 three sets of values - include, exclude, and flatten.

Parameters:

Name Type Description Default
items Union[list[str], str, tuple[str], set[str], dict]

values to be included, excluded or flattened

required
model_cls type[Model]

source model from which relations are constructed

required
slot Slot

which slot to write parsed values into

'include'
Source code in ormar/models/excludable.py
Python
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
def build(
    self,
    items: Union[list[str], str, tuple[str], set[str], dict],
    model_cls: type["Model"],
    slot: Slot = "include",
) -> 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 three sets of values - include, exclude, and flatten.

    :param items: values to be included, excluded or flattened
    :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 slot: which slot to write parsed values into
    :type slot: Slot
    """
    if isinstance(items, str):
        items = {items}

    if isinstance(items, dict):
        self._traverse_dict(
            values=items,
            source_model=model_cls,
            model_cls=model_cls,
            slot=slot,
        )
    else:
        items = set(items)
        nested_items = set(x for x in items if "__" in x)
        items.difference_update(nested_items)
        if items:
            self._set_slot(
                items=items,
                model_cls=model_cls,
                slot=slot,
            )
        if nested_items:
            self._traverse_list(values=nested_items, model_cls=model_cls, slot=slot)

    if slot == "flatten":
        self._validate_flatten_prefix_collisions()

flatten_map()

Return a :class:FlattenMap over the stored flatten paths, built lazily on first call and cached for reuse. The cache is invalidated whenever _set_slot adds a new flatten path. Returns None when no flatten paths are stored, so callers can short-circuit.

Returns:

Type Description
Optional[FlattenMap]

FlattenMap wrapping the nested-Ellipsis dict, or None when no flatten paths are stored

Source code in ormar/models/excludable.py
Python
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
def flatten_map(self) -> Optional[FlattenMap]:
    """
    Return a :class:`FlattenMap` over the stored flatten paths, built
    lazily on first call and cached for reuse. The cache is invalidated
    whenever ``_set_slot`` adds a new flatten path. Returns ``None`` when
    no flatten paths are stored, so callers can short-circuit.

    :return: FlattenMap wrapping the nested-Ellipsis dict, or ``None``
        when no flatten paths are stored
    :rtype: Optional[FlattenMap]
    """
    if not self._flatten_paths:
        return None
    if self._flatten_map_cache is None:
        self._flatten_map_cache = FlattenMap(
            data=build_flatten_map(self._flatten_paths)
        )
    return self._flatten_map_cache

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
Python
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
@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()
    new_excludable._flatten_paths = set(other._flatten_paths)
    new_excludable._included_relation_paths = set(other._included_relation_paths)
    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
Python
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
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 = self._make_key(model_cls, alias)
    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
Python
375
376
377
378
379
380
381
382
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

included_relation_paths()

Returns the relation paths that fields included with fields() are nested in, e.g. {"category__created_by"} for fields(["category__created_by__name"]).

Returns:

Type Description
set[str]

dunder relation paths of the included nested fields

Source code in ormar/models/excludable.py
Python
384
385
386
387
388
389
390
391
392
393
def included_relation_paths(self) -> set[str]:
    """
    Returns the relation paths that fields included with ``fields()``
    are nested in, e.g. ``{"category__created_by"}`` for
    ``fields(["category__created_by__name"])``.

    :return: dunder relation paths of the included nested fields
    :rtype: set[str]
    """
    return {"__".join(path_parts) for path_parts in self._included_relation_paths}

validate_flatten_vs_excludable(source_model)

Ensure no flattened relation has sub-field include/exclude on its target. Whole-relation include/exclude at the parent level is allowed; only sub-field selection on the flattened child is flagged.

Parameters:

Name Type Description Default
source_model type[Model]

model from which flatten paths are rooted

required

Raises:

Type Description
QueryDefinitionError

when a flattened relation has sub-field include/exclude on its target model

Source code in ormar/models/excludable.py
Python
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
def validate_flatten_vs_excludable(self, source_model: type["Model"]) -> None:
    """
    Ensure no flattened relation has sub-field include/exclude on its target.
    Whole-relation include/exclude at the parent level is allowed; only
    sub-field selection on the flattened child is flagged.

    :param source_model: model from which flatten paths are rooted
    :type source_model: type[Model]
    :raises QueryDefinitionError: when a flattened relation has sub-field
        include/exclude on its target model
    """
    for parts in self._flatten_paths:
        table_prefix, target_model, _, _ = get_relationship_alias_model_and_str(
            source_model=source_model,
            related_parts=list(parts),
        )
        child = self.items.get(self._make_key(target_model, table_prefix))
        if not child:
            continue
        conflicts = (child.include | child.exclude) - {...}
        if conflicts:
            raise QueryDefinitionError(
                f"Flatten conflict: relation '{join_path(parts)}' is "
                f"flattened but include/exclude specifies children "
                f"{sorted(conflicts)}. A flattened relation renders only "
                f"its primary key and cannot have children selected."
            )

with_entry_alias(model_cls, source_alias, target_alias)

Returns a copy in which the entry of a model stored under one alias is also stored under another one. Used when a model is queried from a different root than the one the include/exclude paths were defined from (prefetch queries).

Parameters:

Name Type Description Default
model_cls type[Model]

model which entry should be re-aliased

required
source_alias str

alias the entry is stored under

required
target_alias str

alias the entry should be available under

required

Returns:

Type Description
ExcludableItems

copy of excludable items with the re-aliased entry

Source code in ormar/models/excludable.py
Python
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
def with_entry_alias(
    self, model_cls: type["Model"], source_alias: str, target_alias: str
) -> "ExcludableItems":
    """
    Returns a copy in which the entry of a model stored under one alias is also
    stored under another one. Used when a model is queried from a different root
    than the one the include/exclude paths were defined from (prefetch queries).

    :param model_cls: model which entry should be re-aliased
    :type model_cls: type[Model]
    :param source_alias: alias the entry is stored under
    :type source_alias: str
    :param target_alias: alias the entry should be available under
    :type target_alias: str
    :return: copy of excludable items with the re-aliased entry
    :rtype: ExcludableItems
    """
    new_excludable = ExcludableItems.from_excludable(self)
    source = self.items.get(self._make_key(model_cls, source_alias))
    new_excludable.items[self._make_key(model_cls, target_alias)] = (
        source.get_copy() if source else Excludable()
    )
    return new_excludable

with_projection_exclusions(source_model, select_related)

Return a copy with relations not referenced by fields() removed from a flat values projection.

A filter like filter(project__id=...) auto-joins project; without this, a flat values() call leaks every Project column even though only one main-model field was requested. Returns the original instance unchanged when fields() was never called - the leak is a values-projection problem, not an ORM-load problem.

Parameters:

Name Type Description Default
source_model type[Model]

model from which relation paths are rooted

required
select_related list[str]

paths joined into the query (dunder strings)

required

Returns:

Type Description
ExcludableItems

new :class:ExcludableItems with implicit excludes added, or self when no fields() call had any effect

Source code in ormar/models/excludable.py
Python
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
def with_projection_exclusions(
    self,
    source_model: type["Model"],
    select_related: list[str],
) -> "ExcludableItems":
    """
    Return a copy with relations not referenced by ``fields()`` removed
    from a flat values projection.

    A filter like ``filter(project__id=...)`` auto-joins ``project``;
    without this, a flat ``values()`` call leaks every Project column
    even though only one main-model field was requested. Returns the
    original instance unchanged when ``fields()`` was never called -
    the leak is a values-projection problem, not an ORM-load problem.

    :param source_model: model from which relation paths are rooted
    :type source_model: type[Model]
    :param select_related: paths joined into the query (dunder strings)
    :type select_related: list[str]
    :return: new :class:`ExcludableItems` with implicit excludes added,
        or ``self`` when no ``fields()`` call had any effect
    :rtype: ExcludableItems
    """
    if self.include_entry_count() == 0:
        return self

    excludable = ExcludableItems.from_excludable(self)

    # If fields() never names the source model, project only its PK.
    if not excludable._referenced_at(source_model, ()):
        excludable.get(source_model).pk_only = True

    for path in select_related:
        parts = tuple(path.split("__"))
        # Snapshot which prefixes carry a fields() reference before any
        # exclusions are added below - the exclude additions would
        # otherwise show up as "referenced" on the next iteration.
        referenced = [
            excludable._referenced_at(source_model, parts[: d + 1])
            for d in range(len(parts))
        ]
        # Walk deepest-first so kept_deeper accumulates inward. Each
        # segment still needs its own exclude when not kept, because
        # values_column_map only consults the immediate parent.
        kept_deeper = False
        for i in reversed(range(len(parts))):
            kept_deeper = kept_deeper or referenced[i]
            segment = parts[i]
            parent_alias, parent_model = excludable._resolve_path(
                source_model, parts[:i]
            )
            parent_exc = excludable.get(parent_model, alias=parent_alias)
            if parent_exc.is_explicitly_included(segment):
                continue
            if kept_deeper:
                # Intermediate relation: keep the join but project
                # PK-only when this segment was never explicitly named.
                if not referenced[i]:
                    target_alias, target_model = excludable._resolve_path(
                        source_model, parts[: i + 1]
                    )
                    excludable.get(target_model, alias=target_alias).pk_only = True
                continue
            field = parent_model.ormar_config.model_fields[segment]
            parent_exc.exclude.add(segment)
            if field.is_multi:
                parent_exc.exclude.add(field.through.get_name())

    return excludable

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)

ModelRow

Bases: NewBaseModel

Source code in ormar/models/model_row.py
Python
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
class ModelRow(NewBaseModel):
    @classmethod
    def from_row(  # noqa: CFQ002
        cls,
        row: ResultProxy,
        source_model: type["Model"],
        select_related: Optional[list] = None,
        related_models: Any = None,
        related_field: Optional["ForeignKeyField"] = None,
        excludable: Optional[ExcludableItems] = None,
        current_relation_str: str = "",
        proxy_source_model: Optional[type["Model"]] = None,
        plan_cache: Optional[PlanCache] = None,
        registry: Optional[RowRegistry] = None,
        scope: Any = 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 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
        :param plan_cache: optional per-queryset plan cache
        :type plan_cache: Optional[PlanCache]
        :param registry: optional per-query identity map; when passed, a model
            already built for the same relation path and pk is reused and only
            new reverse/many-to-many children from this row are attached to it
        :type registry: Optional[RowRegistry]
        :param scope: registry key of the closest parent reached through a
            many-to-many relation, ``None`` outside of such relations
        :type scope: Any
        :return: returns model if model is populated from database
        :rtype: Optional[Model]
        """
        if select_related:
            related_models = group_related_list(select_related)
        instance, _ = cls._materialize_row(
            row=row,
            source_model=source_model,
            related_models=related_models or [],
            related_field=related_field,
            excludable=excludable or ExcludableItems(),
            current_relation_str=current_relation_str,
            proxy_source_model=proxy_source_model,
            plan_cache=plan_cache,
            registry=registry,
            scope=scope,
        )
        return instance

    @classmethod
    def from_flat_rows(
        cls,
        rows: Sequence[Any],
        excludable: ExcludableItems,
        plan_cache: Optional[PlanCache],
        registry: RowRegistry,
    ) -> list["Model"]:
        """
        Build models of a query without joined relations of a model with
        ``trusted_row_construction()``.

        Without joins every row is one model, so what ``from_row`` does per row
        is not needed here: looking up the extraction plan, the identity map,
        building nested models and merging rows of the same model. One plan
        is looked up for all the rows and each row becomes a model directly::

            await Author.objects.all()
            # rows [{"id": 1, "name": "a"}, {"id": 2, "name": "b"}]
            # -> [Author(id=1, name="a"), Author(id=2, name="b")]

        Foreign key values become pk-only related models, one per related pk
        shared by every row of the query (kept in ``registry``), registered
        on both sides. Repeated primary keys (views or tables without a
        unique pk) keep the first row, like merging does.

        :param rows: database rows of the main model only
        :type rows: Sequence[Any]
        :param excludable: structure of fields to include and exclude
        :type excludable: ExcludableItems
        :param plan_cache: per-queryset plan cache
        :type plan_cache: Optional[PlanCache]
        :param registry: identity map of the query, sharing pk-only related
            models between rows
        :type registry: RowRegistry
        :return: models built from the rows
        :rtype: list[Model]
        """
        plan = cls.get_or_build_row_plan(
            table_prefix="", excludable=excludable, plan_cache=plan_cache
        )
        mappings = plan.column_mappings
        foreign_keys = plan.foreign_key_names
        read_pk = cast(Callable[[Mapping[str, Any]], Any], plan.read_pk_from_item)
        seen: set[Any] = set()
        instances: list["Model"] = []
        for row in rows:
            item = {field_name: row[column] for column, field_name in mappings}
            if plan.multi_column_keys:
                read_multi_column_keys(plan=plan, row=row, item=item)
            pk = read_pk(item)
            if pk in seen:
                continue
            seen.add(pk)
            if foreign_keys:
                cls._share_pk_only_models(
                    plan=plan, item=item, registry=registry, position=(None, "")
                )
            instance = cast("Model", cls.construct_row_instance(plan=plan, item=item))
            object.__setattr__(instance, "_orm_saved", True)
            object.__setattr__(instance, "_orm_persisted", True)
            object.__setattr__(instance, "__ormar_excludable__", excludable)
            instances.append(instance)
        return instances

    @classmethod
    def construct_row_instance(
        cls, plan: RowExtractionPlan, item: dict[str, Any]
    ) -> "ModelRow":
        """
        Build the model instance of one row.

        For models with ``trusted_row_construction()`` the instance is built
        directly from the row values (``_construct_from_row``), as long as the
        row holds every required field. Otherwise it goes
        through ``_construct_with_excluded``, which validates the values,
        registers relations and raises for excluded required fields.

        When the plan already holds every required field, the cached trust of
        the model is enough and the row is not checked again; a model whose
        trust was reset (``reset_relation_caches``) is checked again first.

        :param plan: extraction plan of the row position
        :type plan: RowExtractionPlan
        :param item: field values of the row
        :type item: dict[str, Any]
        :return: model instance
        :rtype: ModelRow
        """
        if (
            plan.holds_required_fields and cls.__dict__.get("_trusted_rows")
        ) or cls.constructs_from_row(item=item):
            return cls._construct_from_row(
                excluded=plan.excluded_field_names, values=item
            )
        return cls._construct_with_excluded(excluded=plan.excluded_field_names, **item)

    @classmethod
    def constructs_from_row(cls, item: dict[str, Any]) -> bool:
        """
        Return whether the instance of a row is built directly from the row
        values: the model allows ``trusted_row_construction()`` and the row
        holds every required field.

        :param item: field values of the row
        :type item: dict[str, Any]
        :return: whether ``_construct_from_row`` builds the instance
        :rtype: bool
        """
        return cls.trusted_row_construction() and cls._required_row_fields.issubset(
            item
        )

    @classmethod
    def _materialize_row(  # noqa: CFQ002
        cls,
        row: ResultProxy,
        source_model: type["Model"],
        related_models: Any,
        related_field: Optional["ForeignKeyField"],
        excludable: ExcludableItems,
        current_relation_str: str,
        proxy_source_model: Optional[type["Model"]],
        plan_cache: Optional[PlanCache],
        registry: Optional[RowRegistry],
        scope: Any,
    ) -> tuple[Optional["Model"], bool]:
        """
        Builds a model (and its selected relations) from a database row, or
        reuses the model already built for the same relation path and pk.

        :param row: raw result row from the database
        :type row: ResultProxy
        :param source_model: model on which relation was defined
        :type source_model: type[Model]
        :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: Optional[ForeignKeyField]
        :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 proxy_source_model: source model from which querysetproxy is constructed
        :type proxy_source_model: Optional[type[Model]]
        :param plan_cache: optional per-queryset plan cache
        :type plan_cache: Optional[PlanCache]
        :param registry: optional per-query identity map
        :type registry: Optional[RowRegistry]
        :param scope: registry key of the closest parent reached through a
            many-to-many relation, ``None`` outside of such relations
        :type scope: Any
        :return: the model (``None`` if the row has no pk for it) and a flag
            whether it was reused from the registry, i.e. built from an
            earlier row and already registered on its parent
        :rtype: tuple[Optional[Model], bool]
        """
        table_prefix = alias_for(current_relation_str) if related_field else ""

        plan = cls.get_or_build_row_plan(table_prefix, excludable, plan_cache)
        key: Optional[RegistryKey] = None
        if registry is not None and plan.read_pk_from_row is not None:
            pk = plan.read_pk_from_row(row)
            if pk is None:
                return None, False
            key = (scope, table_prefix, pk)
            existing = registry.instances.get(key)
            if existing is not None:
                if cls._selects_multi_relation(registry, table_prefix, related_models):
                    children, reused = cls._populate_nested_models_from_row(
                        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,
                        plan_cache=plan_cache,
                        registry=registry,
                        parent_key=key,
                        scope=scope,
                    )
                    cls._attach_children(existing, children, reused)
                return existing, True

        item, _ = cls._populate_nested_models_from_row(
            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,
            plan_cache=plan_cache,
            registry=registry,
            parent_key=key,
            scope=scope,
        )
        item = cls.apply_row_plan(plan, row, item)
        if registry is not None and plan.foreign_key_names:
            cls._share_pk_only_models(plan, item, registry, (scope, table_prefix))

        instance: Optional["Model"] = None
        if (
            plan.read_pk_from_item is not None
            and plan.read_pk_from_item(item) is not None
        ):
            instance = cast("Model", cls.construct_row_instance(plan=plan, item=item))
            instance.set_save_status(True)
            if key is not None:
                registry.instances[key] = instance  # type: ignore[union-attr]
        return instance, False

    @classmethod
    def _share_pk_only_models(
        cls,
        plan: RowExtractionPlan,
        item: dict,
        registry: RowRegistry,
        position: tuple[Any, str],
    ) -> None:
        """
        Replaces raw foreign key values of not selected relations with pk-only
        related models shared by every row of the query that points to the
        same pk from the same position.

        :param plan: extraction plan of the model being built
        :type plan: RowExtractionPlan
        :param item: model kwargs read from the row, updated in place
        :type item: dict
        :param registry: per-query identity map
        :type registry: RowRegistry
        :param position: scope and table prefix of the model being built
        :type position: tuple[Any, str]
        """
        model_fields = cls.ormar_config.model_fields
        instances = registry.instances
        for field_name in plan.foreign_key_names:
            value = item[field_name]
            field = cast("ForeignKeyField", model_fields[field_name])
            if value is None or value.__class__ is field.to:
                continue
            key = (position, field_name, value)
            related = instances.get(key)
            if related is None:
                related = field.construct_key_only_model(value=value)
                instances[key] = related
            item[field_name] = related

    @classmethod
    def _selects_multi_relation(
        cls, registry: RowRegistry, table_prefix: str, related_models: Any
    ) -> bool:
        """
        Memoized per query check if relations selected below this model contain
        a reverse or many-to-many relation that a repeated row can extend.

        :param registry: per-query identity map holding the memo
        :type registry: RowRegistry
        :param table_prefix: alias of the model table in the query
        :type table_prefix: str
        :param related_models: selected relations as list or nested dict
        :type related_models: Union[list, dict]
        :return: True if repeated rows may carry new children for this model
        :rtype: bool
        """
        memo_key = (cls, table_prefix)
        result = registry.subtree_has_multi.get(memo_key)
        if result is None:
            result = selects_multi_relation(cls, related_models)
            registry.subtree_has_multi[memo_key] = result
        return result

    @classmethod
    def _attach_children(
        cls, instance: "Model", children: dict, reused: AbstractSet[str]
    ) -> None:
        """
        Registers children read from a repeated row on an already built model.

        Only reverse, many-to-many and through relations can bring new children;
        a forward foreign key of the same model always resolves to the same,
        already registered instance. Children reused from the registry were
        registered on this model by the row that built them, so they are skipped.

        :param instance: model built from an earlier row
        :type instance: Model
        :param children: related models read from the current row by field name
        :type children: dict
        :param reused: names of relations whose child was reused from the registry
        :type reused: AbstractSet[str]
        """
        model_fields = cls.ormar_config.model_fields
        for name, child in children.items():
            if name in reused:
                continue
            field = model_fields[name]
            if child is not None and (
                field.is_multi or field.virtual or field.is_through
            ):
                field.expand_relationship(child, instance, to_register=True)

    @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,
        current_relation_str: Optional[str] = None,
        proxy_source_model: Optional[type["Model"]] = None,
        plan_cache: Optional[PlanCache] = None,
        registry: Optional[RowRegistry] = None,
        parent_key: Optional[RegistryKey] = None,
        scope: Any = None,
    ) -> tuple[dict, set[str]]:
        """
        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]
        :param plan_cache: optional per-queryset plan cache
        :type plan_cache: Optional[PlanCache]
        :param registry: optional per-query identity map
        :type registry: Optional[RowRegistry]
        :param parent_key: registry key of the model the children belong to,
            used as the scope of children reached through many-to-many
        :type parent_key: Optional[RegistryKey]
        :param scope: registry scope of the model the children belong to
        :type scope: Any
        :return: dictionary with keys corresponding to model fields names
            and values are database values, and names of relations whose
            child was reused from the registry
        :rtype: tuple[dict, set[str]]
        """
        reused: set[str] = set()

        for related in related_models:
            field = cls.ormar_config.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, child_reused = model_cls._materialize_row(
                row=row,
                source_model=source_model,
                related_models=remainder or [],
                related_field=field,
                excludable=excludable,
                current_relation_str=relation_str,
                proxy_source_model=proxy_source_model,
                plan_cache=plan_cache,
                registry=registry,
                scope=parent_key if field.is_multi else scope,
            )
            item[related] = child
            if child_reused:
                reused.add(related)
            elif (
                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,
                    relation_str=relation_str,
                    excludable=excludable,
                    child=child,
                    proxy_source_model=proxy_source_model,
                    plan_cache=plan_cache,
                )

        return item, reused

    @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,
        relation_str: str,
        excludable: ExcludableItems,
        child: "Model",
        proxy_source_model: Optional[type["Model"]],
        plan_cache: Optional[PlanCache] = None,
    ) -> 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 relation_str: path of the many to many relation from the query root
        :type relation_str: 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"]
        :param plan_cache: optional per-queryset plan cache
        :type plan_cache: Optional[PlanCache]
        """
        through_name = cls.ormar_config.model_fields[related].through.get_name()
        through_child = cls._create_through_instance(
            row=row,
            through_name=through_name,
            relation_str=relation_str,
            excludable=excludable,
            plan_cache=plan_cache,
        )

        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,
        relation_str: str,
        excludable: ExcludableItems,
        plan_cache: Optional[PlanCache] = None,
    ) -> "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 relation_str: path of the many to many relation from the query root
        :type relation_str: str
        :param excludable: structure of fields to include and exclude
        :type excludable: ExcludableItems
        :param plan_cache: optional per-queryset plan cache
        :type plan_cache: Optional[PlanCache]
        :return: initialized through model without relation
        :rtype: "ModelRow"
        """
        model_cls = cls.ormar_config.model_fields[through_name].to
        table_prefix = alias_for(f"{relation_str}__{through_name}")
        # remove relations on through field — must happen before the plan is
        # built so the plan reflects the through-model's full exclude set
        model_excludable = excludable.get(model_cls=model_cls, alias=table_prefix)
        model_excludable.set_values(
            value=model_cls.extract_related_names(), slot="exclude"
        )
        plan = model_cls.get_or_build_row_plan(table_prefix, excludable, plan_cache)
        child_dict = model_cls.apply_row_plan(plan, row, {})
        child = model_cls._construct_with_excluded(  # type: ignore
            plan.excluded_field_names, **child_dict
        )
        return child

    @classmethod
    def build_row_extraction_plan(
        cls,
        table_prefix: str,
        excludable: ExcludableItems,
    ) -> RowExtractionPlan:
        """
        Compute the per-row extraction plan for a ``(cls, table_prefix,
        excludable)`` triple — the work that previously ran inside
        ``extract_prefixed_table_columns`` for every row.

        :param table_prefix: alias of the table from alias_for
        :type table_prefix: str
        :param excludable: structure of fields to include and exclude
        :type excludable: ExcludableItems
        :return: cacheable plan for fast per-row extraction
        :rtype: RowExtractionPlan
        """
        selected_columns = set(
            cls.own_table_columns(
                model=cls, excludable=excludable, alias=table_prefix, use_alias=False
            )
        )
        column_prefix = table_prefix + "_" if table_prefix else ""
        column_pairs = cls._get_table_column_pairs(cls)
        all_mappings = tuple(
            (f"{column_prefix}{col_name}", field_name)
            for col_name, field_name in column_pairs
            if field_name in selected_columns
        )
        column_counts = Counter(field_name for _, field_name in all_mappings)
        mappings = tuple(pair for pair in all_mappings if column_counts[pair[1]] == 1)
        multi_column_keys = tuple(
            (
                field_name,
                tuple(
                    f"{column_prefix}{column}"
                    for column in cls.ormar_config.model_fields[
                        field_name
                    ].column_aliases()
                ),
            )
            for field_name, count in column_counts.items()
            if count > 1
        )
        excluded = frozenset(
            cls.get_names_to_exclude(excludable=excludable, alias=table_prefix)
        )
        key = cls.ormar_config.pk
        pk_columns: Optional[tuple[str, ...]] = None
        read_pk_from_row = None
        read_pk_from_item = None
        selected = {column for column, _ in all_mappings}
        key_columns = tuple(
            f"{column_prefix}{column}" for column in key.column_aliases()
        )
        if all(column in selected for column in key_columns):
            pk_columns = key_columns
            read_pk_from_row = key.getter(keys=pk_columns)
            read_pk_from_item = key.item_reader()
        model_fields = cls.ormar_config.model_fields
        foreign_key_names = tuple(
            field_name
            for field_name in column_counts
            if model_fields[field_name].is_relation
        )
        cls.trusted_row_construction()  # fills ``_required_row_fields``
        return RowExtractionPlan(
            column_mappings=mappings,
            excluded_field_names=excluded,
            pk_columns=pk_columns,
            read_pk_from_row=read_pk_from_row,
            read_pk_from_item=read_pk_from_item,
            foreign_key_names=foreign_key_names,
            holds_required_fields=cls._required_row_fields.issubset(column_counts),
            multi_column_keys=multi_column_keys,
        )

    @classmethod
    def get_or_build_row_plan(
        cls,
        table_prefix: str,
        excludable: ExcludableItems,
        plan_cache: Optional[PlanCache],
    ) -> RowExtractionPlan:
        """
        Return a plan from the per-queryset cache, falling back to the plans
        shared between querysets. When ``plan_cache`` is ``None`` (legacy /
        external caller) only the shared plans are used.

        :param table_prefix: alias of the table from alias_for
        :type table_prefix: str
        :param excludable: structure of fields to include and exclude
        :type excludable: ExcludableItems
        :param plan_cache: per-queryset cache keyed by
            ``(cls, table_prefix, id(excludable))``; ``None`` to bypass
        :type plan_cache: Optional[PlanCache]
        :return: extraction plan for this row position
        :rtype: RowExtractionPlan
        """
        if plan_cache is None:
            return cls.get_shared_row_plan(table_prefix, excludable)
        key = (cls, table_prefix, id(excludable))
        plan = plan_cache.get(key)
        if plan is None:
            plan = cls.get_shared_row_plan(table_prefix, excludable)
            plan_cache[key] = plan
        return plan

    @classmethod
    def get_shared_row_plan(
        cls, table_prefix: str, excludable: ExcludableItems
    ) -> RowExtractionPlan:
        """
        Return a plan shared between querysets for the model's own
        include/exclude/pk_only settings at the given table prefix.

        :param table_prefix: alias of the table from alias_for
        :type table_prefix: str
        :param excludable: structure of fields to include and exclude
        :type excludable: ExcludableItems
        :return: extraction plan for this row position
        :rtype: RowExtractionPlan
        """
        model_excludable = excludable.get(model_cls=cls, alias=table_prefix)  # type: ignore
        return build_shared_row_plan(
            model_cls=cls,
            table_prefix=table_prefix,
            include=frozenset(model_excludable.include),
            exclude=frozenset(model_excludable.exclude),
            pk_only=model_excludable.pk_only,
        )

    @staticmethod
    def apply_row_plan(
        plan: RowExtractionPlan,
        row: ResultProxy,
        item: dict,
    ) -> dict:
        """
        Populate ``item`` from ``row`` using ``plan.column_mappings``. Skips
        keys already present so a partially populated dict (e.g. from
        ``_populate_nested_models_from_row``) is not overwritten.

        :param plan: precomputed extraction plan
        :type plan: RowExtractionPlan
        :param row: raw result row from the database
        :type row: sqlalchemy.engine.result.ResultProxy
        :param item: dict to populate in place
        :type item: dict
        :return: ``item`` (returned for chaining symmetry with the legacy API)
        :rtype: dict
        """
        for prefixed_name, field_name in plan.column_mappings:
            if field_name not in item:
                item[field_name] = row[prefixed_name]
        if plan.multi_column_keys:
            read_multi_column_keys(plan=plan, row=row, item=item)
        return item

apply_row_plan(plan, row, item) staticmethod

Populate item from row using plan.column_mappings. Skips keys already present so a partially populated dict (e.g. from _populate_nested_models_from_row) is not overwritten.

Parameters:

Name Type Description Default
plan RowExtractionPlan

precomputed extraction plan

required
row Row

raw result row from the database

required
item dict

dict to populate in place

required

Returns:

Type Description
dict

item (returned for chaining symmetry with the legacy API)

Source code in ormar/models/model_row.py
Python
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
@staticmethod
def apply_row_plan(
    plan: RowExtractionPlan,
    row: ResultProxy,
    item: dict,
) -> dict:
    """
    Populate ``item`` from ``row`` using ``plan.column_mappings``. Skips
    keys already present so a partially populated dict (e.g. from
    ``_populate_nested_models_from_row``) is not overwritten.

    :param plan: precomputed extraction plan
    :type plan: RowExtractionPlan
    :param row: raw result row from the database
    :type row: sqlalchemy.engine.result.ResultProxy
    :param item: dict to populate in place
    :type item: dict
    :return: ``item`` (returned for chaining symmetry with the legacy API)
    :rtype: dict
    """
    for prefixed_name, field_name in plan.column_mappings:
        if field_name not in item:
            item[field_name] = row[prefixed_name]
    if plan.multi_column_keys:
        read_multi_column_keys(plan=plan, row=row, item=item)
    return item

build_row_extraction_plan(table_prefix, excludable) classmethod

Compute the per-row extraction plan for a (cls, table_prefix, excludable) triple — the work that previously ran inside extract_prefixed_table_columns for every row.

Parameters:

Name Type Description Default
table_prefix str

alias of the table from alias_for

required
excludable ExcludableItems

structure of fields to include and exclude

required

Returns:

Type Description
RowExtractionPlan

cacheable plan for fast per-row extraction

Source code in ormar/models/model_row.py
Python
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
@classmethod
def build_row_extraction_plan(
    cls,
    table_prefix: str,
    excludable: ExcludableItems,
) -> RowExtractionPlan:
    """
    Compute the per-row extraction plan for a ``(cls, table_prefix,
    excludable)`` triple — the work that previously ran inside
    ``extract_prefixed_table_columns`` for every row.

    :param table_prefix: alias of the table from alias_for
    :type table_prefix: str
    :param excludable: structure of fields to include and exclude
    :type excludable: ExcludableItems
    :return: cacheable plan for fast per-row extraction
    :rtype: RowExtractionPlan
    """
    selected_columns = set(
        cls.own_table_columns(
            model=cls, excludable=excludable, alias=table_prefix, use_alias=False
        )
    )
    column_prefix = table_prefix + "_" if table_prefix else ""
    column_pairs = cls._get_table_column_pairs(cls)
    all_mappings = tuple(
        (f"{column_prefix}{col_name}", field_name)
        for col_name, field_name in column_pairs
        if field_name in selected_columns
    )
    column_counts = Counter(field_name for _, field_name in all_mappings)
    mappings = tuple(pair for pair in all_mappings if column_counts[pair[1]] == 1)
    multi_column_keys = tuple(
        (
            field_name,
            tuple(
                f"{column_prefix}{column}"
                for column in cls.ormar_config.model_fields[
                    field_name
                ].column_aliases()
            ),
        )
        for field_name, count in column_counts.items()
        if count > 1
    )
    excluded = frozenset(
        cls.get_names_to_exclude(excludable=excludable, alias=table_prefix)
    )
    key = cls.ormar_config.pk
    pk_columns: Optional[tuple[str, ...]] = None
    read_pk_from_row = None
    read_pk_from_item = None
    selected = {column for column, _ in all_mappings}
    key_columns = tuple(
        f"{column_prefix}{column}" for column in key.column_aliases()
    )
    if all(column in selected for column in key_columns):
        pk_columns = key_columns
        read_pk_from_row = key.getter(keys=pk_columns)
        read_pk_from_item = key.item_reader()
    model_fields = cls.ormar_config.model_fields
    foreign_key_names = tuple(
        field_name
        for field_name in column_counts
        if model_fields[field_name].is_relation
    )
    cls.trusted_row_construction()  # fills ``_required_row_fields``
    return RowExtractionPlan(
        column_mappings=mappings,
        excluded_field_names=excluded,
        pk_columns=pk_columns,
        read_pk_from_row=read_pk_from_row,
        read_pk_from_item=read_pk_from_item,
        foreign_key_names=foreign_key_names,
        holds_required_fields=cls._required_row_fields.issubset(column_counts),
        multi_column_keys=multi_column_keys,
    )

construct_row_instance(plan, item) classmethod

Build the model instance of one row.

For models with trusted_row_construction() the instance is built directly from the row values (_construct_from_row), as long as the row holds every required field. Otherwise it goes through _construct_with_excluded, which validates the values, registers relations and raises for excluded required fields.

When the plan already holds every required field, the cached trust of the model is enough and the row is not checked again; a model whose trust was reset (reset_relation_caches) is checked again first.

Parameters:

Name Type Description Default
plan RowExtractionPlan

extraction plan of the row position

required
item dict[str, Any]

field values of the row

required

Returns:

Type Description
ModelRow

model instance

Source code in ormar/models/model_row.py
Python
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
@classmethod
def construct_row_instance(
    cls, plan: RowExtractionPlan, item: dict[str, Any]
) -> "ModelRow":
    """
    Build the model instance of one row.

    For models with ``trusted_row_construction()`` the instance is built
    directly from the row values (``_construct_from_row``), as long as the
    row holds every required field. Otherwise it goes
    through ``_construct_with_excluded``, which validates the values,
    registers relations and raises for excluded required fields.

    When the plan already holds every required field, the cached trust of
    the model is enough and the row is not checked again; a model whose
    trust was reset (``reset_relation_caches``) is checked again first.

    :param plan: extraction plan of the row position
    :type plan: RowExtractionPlan
    :param item: field values of the row
    :type item: dict[str, Any]
    :return: model instance
    :rtype: ModelRow
    """
    if (
        plan.holds_required_fields and cls.__dict__.get("_trusted_rows")
    ) or cls.constructs_from_row(item=item):
        return cls._construct_from_row(
            excluded=plan.excluded_field_names, values=item
        )
    return cls._construct_with_excluded(excluded=plan.excluded_field_names, **item)

constructs_from_row(item) classmethod

Return whether the instance of a row is built directly from the row values: the model allows trusted_row_construction() and the row holds every required field.

Parameters:

Name Type Description Default
item dict[str, Any]

field values of the row

required

Returns:

Type Description
bool

whether _construct_from_row builds the instance

Source code in ormar/models/model_row.py
Python
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
@classmethod
def constructs_from_row(cls, item: dict[str, Any]) -> bool:
    """
    Return whether the instance of a row is built directly from the row
    values: the model allows ``trusted_row_construction()`` and the row
    holds every required field.

    :param item: field values of the row
    :type item: dict[str, Any]
    :return: whether ``_construct_from_row`` builds the instance
    :rtype: bool
    """
    return cls.trusted_row_construction() and cls._required_row_fields.issubset(
        item
    )

from_flat_rows(rows, excludable, plan_cache, registry) classmethod

Build models of a query without joined relations of a model with trusted_row_construction().

Without joins every row is one model, so what from_row does per row is not needed here: looking up the extraction plan, the identity map, building nested models and merging rows of the same model. One plan is looked up for all the rows and each row becomes a model directly::

Text Only
1
2
3
await Author.objects.all()
# rows [{"id": 1, "name": "a"}, {"id": 2, "name": "b"}]
# -> [Author(id=1, name="a"), Author(id=2, name="b")]

Foreign key values become pk-only related models, one per related pk shared by every row of the query (kept in registry), registered on both sides. Repeated primary keys (views or tables without a unique pk) keep the first row, like merging does.

Parameters:

Name Type Description Default
rows Sequence[Any]

database rows of the main model only

required
excludable ExcludableItems

structure of fields to include and exclude

required
plan_cache Optional[PlanCache]

per-queryset plan cache

required
registry RowRegistry

identity map of the query, sharing pk-only related models between rows

required

Returns:

Type Description
list[Model]

models built from the rows

Source code in ormar/models/model_row.py
Python
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
@classmethod
def from_flat_rows(
    cls,
    rows: Sequence[Any],
    excludable: ExcludableItems,
    plan_cache: Optional[PlanCache],
    registry: RowRegistry,
) -> list["Model"]:
    """
    Build models of a query without joined relations of a model with
    ``trusted_row_construction()``.

    Without joins every row is one model, so what ``from_row`` does per row
    is not needed here: looking up the extraction plan, the identity map,
    building nested models and merging rows of the same model. One plan
    is looked up for all the rows and each row becomes a model directly::

        await Author.objects.all()
        # rows [{"id": 1, "name": "a"}, {"id": 2, "name": "b"}]
        # -> [Author(id=1, name="a"), Author(id=2, name="b")]

    Foreign key values become pk-only related models, one per related pk
    shared by every row of the query (kept in ``registry``), registered
    on both sides. Repeated primary keys (views or tables without a
    unique pk) keep the first row, like merging does.

    :param rows: database rows of the main model only
    :type rows: Sequence[Any]
    :param excludable: structure of fields to include and exclude
    :type excludable: ExcludableItems
    :param plan_cache: per-queryset plan cache
    :type plan_cache: Optional[PlanCache]
    :param registry: identity map of the query, sharing pk-only related
        models between rows
    :type registry: RowRegistry
    :return: models built from the rows
    :rtype: list[Model]
    """
    plan = cls.get_or_build_row_plan(
        table_prefix="", excludable=excludable, plan_cache=plan_cache
    )
    mappings = plan.column_mappings
    foreign_keys = plan.foreign_key_names
    read_pk = cast(Callable[[Mapping[str, Any]], Any], plan.read_pk_from_item)
    seen: set[Any] = set()
    instances: list["Model"] = []
    for row in rows:
        item = {field_name: row[column] for column, field_name in mappings}
        if plan.multi_column_keys:
            read_multi_column_keys(plan=plan, row=row, item=item)
        pk = read_pk(item)
        if pk in seen:
            continue
        seen.add(pk)
        if foreign_keys:
            cls._share_pk_only_models(
                plan=plan, item=item, registry=registry, position=(None, "")
            )
        instance = cast("Model", cls.construct_row_instance(plan=plan, item=item))
        object.__setattr__(instance, "_orm_saved", True)
        object.__setattr__(instance, "_orm_persisted", True)
        object.__setattr__(instance, "__ormar_excludable__", excludable)
        instances.append(instance)
    return instances

from_row(row, source_model, select_related=None, related_models=None, related_field=None, excludable=None, current_relation_str='', proxy_source_model=None, plan_cache=None, registry=None, scope=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
proxy_source_model Optional[type[Model]]

source model from which querysetproxy is constructed

None
excludable Optional[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 Row

raw result row from the database

required
select_related Optional[list]

list of names of related models fetched from database

None
related_models Any

list or dict of related models

None
related_field Optional[ForeignKeyField]

field with relation declaration

None
plan_cache Optional[PlanCache]

optional per-queryset plan cache

None
registry Optional[RowRegistry]

optional per-query identity map; when passed, a model already built for the same relation path and pk is reused and only new reverse/many-to-many children from this row are attached to it

None
scope Any

registry key of the closest parent reached through a many-to-many relation, None outside of such relations

None

Returns:

Type Description
Optional[Model]

returns model if model is populated from database

Source code in ormar/models/model_row.py
Python
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
@classmethod
def from_row(  # noqa: CFQ002
    cls,
    row: ResultProxy,
    source_model: type["Model"],
    select_related: Optional[list] = None,
    related_models: Any = None,
    related_field: Optional["ForeignKeyField"] = None,
    excludable: Optional[ExcludableItems] = None,
    current_relation_str: str = "",
    proxy_source_model: Optional[type["Model"]] = None,
    plan_cache: Optional[PlanCache] = None,
    registry: Optional[RowRegistry] = None,
    scope: Any = 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 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
    :param plan_cache: optional per-queryset plan cache
    :type plan_cache: Optional[PlanCache]
    :param registry: optional per-query identity map; when passed, a model
        already built for the same relation path and pk is reused and only
        new reverse/many-to-many children from this row are attached to it
    :type registry: Optional[RowRegistry]
    :param scope: registry key of the closest parent reached through a
        many-to-many relation, ``None`` outside of such relations
    :type scope: Any
    :return: returns model if model is populated from database
    :rtype: Optional[Model]
    """
    if select_related:
        related_models = group_related_list(select_related)
    instance, _ = cls._materialize_row(
        row=row,
        source_model=source_model,
        related_models=related_models or [],
        related_field=related_field,
        excludable=excludable or ExcludableItems(),
        current_relation_str=current_relation_str,
        proxy_source_model=proxy_source_model,
        plan_cache=plan_cache,
        registry=registry,
        scope=scope,
    )
    return instance

get_or_build_row_plan(table_prefix, excludable, plan_cache) classmethod

Return a plan from the per-queryset cache, falling back to the plans shared between querysets. When plan_cache is None (legacy / external caller) only the shared plans are used.

Parameters:

Name Type Description Default
table_prefix str

alias of the table from alias_for

required
excludable ExcludableItems

structure of fields to include and exclude

required
plan_cache Optional[PlanCache]

per-queryset cache keyed by (cls, table_prefix, id(excludable)); None to bypass

required

Returns:

Type Description
RowExtractionPlan

extraction plan for this row position

Source code in ormar/models/model_row.py
Python
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
@classmethod
def get_or_build_row_plan(
    cls,
    table_prefix: str,
    excludable: ExcludableItems,
    plan_cache: Optional[PlanCache],
) -> RowExtractionPlan:
    """
    Return a plan from the per-queryset cache, falling back to the plans
    shared between querysets. When ``plan_cache`` is ``None`` (legacy /
    external caller) only the shared plans are used.

    :param table_prefix: alias of the table from alias_for
    :type table_prefix: str
    :param excludable: structure of fields to include and exclude
    :type excludable: ExcludableItems
    :param plan_cache: per-queryset cache keyed by
        ``(cls, table_prefix, id(excludable))``; ``None`` to bypass
    :type plan_cache: Optional[PlanCache]
    :return: extraction plan for this row position
    :rtype: RowExtractionPlan
    """
    if plan_cache is None:
        return cls.get_shared_row_plan(table_prefix, excludable)
    key = (cls, table_prefix, id(excludable))
    plan = plan_cache.get(key)
    if plan is None:
        plan = cls.get_shared_row_plan(table_prefix, excludable)
        plan_cache[key] = plan
    return plan

get_shared_row_plan(table_prefix, excludable) classmethod

Return a plan shared between querysets for the model's own include/exclude/pk_only settings at the given table prefix.

Parameters:

Name Type Description Default
table_prefix str

alias of the table from alias_for

required
excludable ExcludableItems

structure of fields to include and exclude

required

Returns:

Type Description
RowExtractionPlan

extraction plan for this row position

Source code in ormar/models/model_row.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
@classmethod
def get_shared_row_plan(
    cls, table_prefix: str, excludable: ExcludableItems
) -> RowExtractionPlan:
    """
    Return a plan shared between querysets for the model's own
    include/exclude/pk_only settings at the given table prefix.

    :param table_prefix: alias of the table from alias_for
    :type table_prefix: str
    :param excludable: structure of fields to include and exclude
    :type excludable: ExcludableItems
    :return: extraction plan for this row position
    :rtype: RowExtractionPlan
    """
    model_excludable = excludable.get(model_cls=cls, alias=table_prefix)  # type: ignore
    return build_shared_row_plan(
        model_cls=cls,
        table_prefix=table_prefix,
        include=frozenset(model_excludable.include),
        exclude=frozenset(model_excludable.exclude),
        pk_only=model_excludable.pk_only,
    )

NewBaseModel

Bases: 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
Python
 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
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
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_persisted",
        "_orm_persisted_key",
        "_orm",
        "__pk_only__",
        "__ormar_excludable__",
        "__cached_hash__",
        "__pydantic_extra__",
        "__pydantic_fields_set__",
        "__setattr_fields__",
        "__json_snapshot__",
    )

    if TYPE_CHECKING:  # pragma no cover
        pk: Any
        __relation_map__: Optional[list[str]]
        __relation_tree__: Optional[builtins.dict]
        __relation_graph_version__: int
        __cached_hash__: Optional[int]
        __setattr_fields__: set[str]
        __json_snapshot__: Optional[builtins.dict[str, Any]]
        _orm: RelationsManager
        _orm_id: int
        _orm_saved: bool
        _orm_persisted: bool
        _orm_persisted_key: Any
        _related_names: Optional[set]
        _through_names: Optional[set]
        _related_names_hash: str
        _quick_access_fields: set
        _json_fields: set
        _loaded_json_fields: set
        _bytes_fields: set
        _onupdate_fields: set
        _pydantic_field_names: Optional[frozenset[str]]
        _extra_is_ignore: Optional[bool]
        _allowed_kwarg_names: Optional[frozenset[str]]
        _relation_field_names: Optional[frozenset[str]]
        _required_row_fields: frozenset[str]
        _row_relation_names: tuple[str, ...]
        _row_field_order: tuple[str, ...]
        _trusted_rows: Optional[bool]
        ormar_config: OrmarConfig

    # 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 OrmarConfig cannot be initialized.

        :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()

        object.__setattr__(self, "__pk_only__", False)
        object.__setattr__(self, "__ormar_excludable__", None)

        new_kwargs, through_tmp_dict = self._process_kwargs(kwargs)

        decoded = (
            self.serialize_nested_models_json_fields(kwargs=new_kwargs)
            if self.extract_related_fields()
            else []
        )
        try:
            self.__pydantic_validator__.validate_python(
                new_kwargs,
                self_instance=self,  # type: ignore
            )
        finally:
            self.restore_nested_models_json_fields(decoded=decoded)
        self._register_related_models(new_kwargs, through_tmp_dict)

    @classmethod
    def _internal_construct(
        cls,
        _pk_only: bool = False,
        _excluded: Optional[set[str]] = None,
        **kwargs: Any,
    ) -> "NewBaseModel":
        """
        Internal-only factory for constructing model instances with pk_only or
        excluded support. Not reachable from user-supplied kwargs or JSON
        deserialization.

        :param _pk_only: if True, skip validation and set only pk field
        :type _pk_only: bool
        :param _excluded: set of field names to explicitly set to None
        :type _excluded: Optional[set[str]]
        :param kwargs: field values for the model
        :type kwargs: Any
        :return: constructed model instance
        :rtype: NewBaseModel
        """
        instance = cls.__new__(cls)
        instance._verify_model_can_be_initialized()
        instance._initialize_internal_attributes()
        object.__setattr__(instance, "__pk_only__", _pk_only)
        object.__setattr__(instance, "__ormar_excludable__", None)

        new_kwargs, through_tmp_dict = instance._process_kwargs(kwargs)

        if _excluded:
            for field_to_nullify in _excluded:
                new_kwargs[field_to_nullify] = None

        if not _pk_only:
            decoded = (
                instance.serialize_nested_models_json_fields(kwargs=new_kwargs)
                if instance.extract_related_fields()
                else []
            )
            try:
                instance.__pydantic_validator__.validate_python(
                    new_kwargs,
                    self_instance=instance,  # type: ignore
                )
            finally:
                instance.restore_nested_models_json_fields(decoded=decoded)
        else:
            related_names = instance.extract_related_names()
            fields_set = {
                name
                for name in kwargs
                if name in instance.ormar_config.model_fields
                and name not in related_names
            }
            object.__setattr__(instance, "__dict__", new_kwargs)
            object.__setattr__(instance, "__pydantic_fields_set__", fields_set)

        instance._register_related_models(new_kwargs, through_tmp_dict)
        return instance

    def _register_related_models(
        self, new_kwargs: dict[str, Any], through_tmp_dict: dict[str, Any]
    ) -> None:
        """
        Adds back through fields and registers related models after initialization.

        :param new_kwargs: processed keyword arguments with field values
        :type new_kwargs: dict[str, Any]
        :param through_tmp_dict: through model fields extracted during processing
        :type through_tmp_dict: dict[str, Any]
        """
        new_kwargs.update(through_tmp_dict)
        for field in self.extract_related_fields():
            field.expand_relationship(
                value=new_kwargs.get(field.name), child=self, to_register=True
            )

    @classmethod
    def trusted_row_construction(cls) -> bool:
        """
        Return whether rows of this model can be turned into instances without
        running ``__init__``.

        A database row is already converted by the column types (an Integer
        column returns ``int``, a DateTime one ``datetime``), so pydantic's
        validation would hand back the same values. Skipping it is only safe
        when nothing on the model could change a value or has side effects,
        so the model must have none of:

        - through fields or a custom ``__init__``
        - validators of any kind, private attributes or ``model_post_init``
        - extra fields (``extra="allow"``)
        - fields whose pydantic type differs from the column type, encrypted
          fields or fields represented as base64 strings
        - value-changing model config (``VALUE_CHANGING_CONFIG``: enum values,
          string transformations, number coercion, strict mode)

        Computed once per class, together with the per-class lookups the
        trusted path uses (required fields, relation names and field order).
        Defining a related model later resets it (see
        ``reset_relation_caches``)::

            class Author(ormar.Model):
                ormar_config = base_ormar_config.copy(tablename="authors")

                id: int = ormar.Integer(primary_key=True)
                name: str = ormar.String(max_length=100)


            Author.trusted_row_construction()  # -> True

        :return: True when database rows can be trusted as field values
        :rtype: bool
        """
        cached = cls.__dict__.get("_trusted_rows")
        if cached is not None:
            return cast(bool, cached)
        decorators = cls.__pydantic_decorators__
        model_fields = cls.ormar_config.model_fields
        trusted = (
            cls.__init__ is NewBaseModel.__init__
            and not cls.extract_through_names()
            and set(cls.model_fields) == set(model_fields)
            and all(
                (field.is_relation or field.__pydantic_type__ is field.__type__)
                and not field.encrypt_secret
                and not field.represent_as_base64_str
                for field in model_fields.values()
            )
            and not (
                decorators.validators
                or decorators.field_validators
                or decorators.root_validators
                or decorators.model_validators
            )
            and not cls.__private_attributes__
            and cls.__pydantic_post_init__ is None
            and cls.model_config.get("extra") != "allow"
            and not any(cls.model_config.get(key) for key in VALUE_CHANGING_CONFIG)
        )
        type.__setattr__(
            cls,
            "_required_row_fields",
            frozenset(
                name for name, info in cls.model_fields.items() if info.is_required()
            ),
        )
        type.__setattr__(cls, "_row_relation_names", tuple(cls.extract_related_names()))
        type.__setattr__(cls, "_row_field_order", tuple(cls.model_fields))
        type.__setattr__(cls, "_trusted_rows", trusted)
        return trusted

    @classmethod
    def flat_row_model(cls) -> bool:
        """
        Return whether the model has ``trusted_row_construction()``, no
        relations at all and no custom serialization (serializers or an
        overridden ``model_dump``), so its rows and its ``model_dump()`` hold
        plain column values only.

        For such models ``bulk_create`` copies each instance's ``__dict__``
        instead of calling ``model_dump()`` (see ``dump_for_save``).

        :return: True for trusted models without relations
        :rtype: bool
        """
        decorators = cls.__pydantic_decorators__
        return (
            cls.trusted_row_construction()
            and not cls._row_relation_names
            and not decorators.field_serializers
            and not decorators.model_serializers
            and cls.model_dump is NewBaseModel.model_dump
        )

    @classmethod
    def _construct_from_row(
        cls, excluded: AbstractSet[str], values: dict[str, Any]
    ) -> typing_extensions.Self:
        """
        Build an instance straight from database row values, which the column
        types already converted, skipping ``__init__`` and validation. Only for
        models with ``trusted_row_construction()`` and rows holding every
        required field.

        The instance gets the state ``__init__`` would leave behind: internal
        ormar attributes, the values as pydantic's ``__dict__`` and the row's
        fields as ``model_fields_set``. Fields missing from the row or
        excluded are None, like after ``_construct_with_excluded``. When the
        row holds every field in field order, the row dict itself becomes the
        ``__dict__`` without a copy.

        Relation values (a related model, or the raw pk of a foreign key) are
        expanded to models and registered on both sides, like ``__init__``
        does after validation. An empty reverse relation becomes ``[]``::

            book = Book._construct_from_row(
                excluded=frozenset(), values={"id": 1, "title": "t", "author": 2}
            )
            book.author  # -> pk-only Author(id=2), with book in author.books

        :param excluded: field names excluded from the query
        :type excluded: AbstractSet[str]
        :param values: field values of the row, used as the instance's
            ``__dict__`` when it holds every field in field order; relation
            values are replaced with their expanded models
        :type values: dict[str, Any]
        :return: model instance
        :rtype: Self
        """
        instance = cls.__new__(cls)
        instance._initialize_internal_attributes()
        object.__setattr__(instance, "__pk_only__", False)
        object.__setattr__(instance, "__ormar_excludable__", None)
        relation_fields = cls.ormar_config.model_fields
        related = {
            name: relation_fields[name].expand_relationship(
                value=values[name], child=instance, to_register=False
            )
            for name in cls._row_relation_names
            if name in values
        }
        if related:
            values.update(related)
        field_order = cls._row_field_order
        if not excluded and tuple(values) == field_order:
            data = values
        else:
            data = {
                name: None if name in excluded else values.get(name)
                for name in field_order
            }
        object.__setattr__(instance, "__dict__", data)
        object.__setattr__(instance, "__pydantic_fields_set__", set(values))
        object.__setattr__(instance, "__pydantic_extra__", None)
        object.__setattr__(instance, "__pydantic_private__", None)
        for name, model in related.items():
            if model is not None and not isinstance(model, list):
                relation_fields[name].expand_relationship(
                    value=model, child=instance, to_register=True
                )
        if cls._json_fields and cls.ormar_config.partial_updates:
            instance._snapshot_json_fields()
        return instance

    @classmethod
    def _construct_with_excluded(
        cls, excluded: AbstractSet[str], **kwargs: Any
    ) -> typing_extensions.Self:
        """
        Constructs model instance and nullifies excluded fields post-construction.
        Used when loading results from the database.

        Values of plain JSON fields are already decoded by the sqlalchemy column
        type, so they are kept aside during validation and assigned afterwards
        instead of being encoded back to a string only for pydantic to parse them
        again. JSON fields with an overwritten pydantic type or encryption still
        go through validation.

        :param excluded: collection of field names to nullify after construction
        :type excluded: AbstractSet[str]
        :param kwargs: field values for the model
        :type kwargs: Any
        :return: constructed model instance
        :rtype: Self
        """
        loaded_json = {
            name: kwargs[name] for name in cls._loaded_json_fields if name in kwargs
        }
        for name in loaded_json:
            kwargs[name] = None
        instance = cls(**kwargs)
        instance.__dict__.update(loaded_json)
        for field_to_nullify in excluded:
            instance.__dict__[field_to_nullify] = None
        if cls._json_fields and cls.ormar_config.partial_updates:
            instance._snapshot_json_fields()
        return instance

    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 name in self.ormar_config.pk.fields:
            self.remember_persisted_key()

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

        if name in self.ormar_config.model_fields:
            self.__setattr_fields__.add(name)

        # In this case, the hash could have changed, so update it
        if name in self.ormar_config.pk.fields 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 for private attributes of pydantic v2.

        :param item: name of attribute
        :type item: str
        :return: Any
        :rtype: Any
        """
        # TODO: Check __pydantic_extra__
        if item == "__pydantic_extra__":
            return None
        return super().__getattr__(item)  # type: ignore

    def __getstate__(self) -> dict[Any, Any]:
        state = super().__getstate__()
        self_dict = self.model_dump()
        state["__dict__"].update(**self_dict)
        state["__ormar_persisted__"] = (self._orm_persisted, self._orm_persisted_key)
        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
        persisted, persisted_key = state.pop("__ormar_persisted__", (False, None))
        super().__setstate__(state)
        self._initialize_internal_attributes()
        object.__setattr__(self, "_orm_persisted", persisted)
        object.__setattr__(self, "_orm_persisted_key", persisted_key)
        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:
                # Read ``related_models`` directly (rather than calling
                # ``relation.get()``) so an un-materialized reverse/m2m
                # proxy stays un-materialized — there is nothing in an
                # empty proxy to migrate hashes for.
                relation_proxy = relation.related_models
                if is_dead_proxy(relation_proxy):
                    continue
                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 _snapshot_json_fields(self) -> None:
        """
        Remembers a copy of the json field values as they are in the database,
        so that partial updates can detect values mutated in place
        (``model.data["key"] = 1``), which do not go through ``__setattr__``.

        Called only for models with ``partial_updates=True`` and json fields;
        the copy is the price of loading such a row.
        """
        object.__setattr__(
            self,
            "__json_snapshot__",
            {
                name: copy.deepcopy(self.__dict__.get(name))
                for name in self._json_fields
            },
        )

    def _reset_change_tracking(self) -> None:
        """
        Marks the model as in sync with its database row: forgets the fields
        assigned since the last load or save and snapshots json fields again.
        """
        self.__setattr_fields__.clear()
        if self._json_fields and self.ormar_config.partial_updates:
            self._snapshot_json_fields()

    def _changed_fields(self) -> set[str]:
        """
        Returns the fields changed since the model was last loaded or saved:
        the ones assigned through ``__setattr__`` and json fields whose value
        differs from the snapshot taken at load.

        :return: names of changed fields
        :rtype: set[str]
        """
        changed = set(self.__setattr_fields__)
        snapshot = self.__json_snapshot__
        if snapshot:
            changed.update(
                name
                for name, value in snapshot.items()
                if self.__dict__.get(name) != value
            )
        return changed

    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.ormar_config.abstract:
            raise ModelError(f"You cannot initialize abstract model {self.get_name()}")
        if self.ormar_config.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 pydantic fields.

        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]
        """
        cls = type(self)
        config = cls.ormar_config
        model_fields = config.model_fields

        pydantic_fields = cls._pydantic_field_names
        if pydantic_fields is None:
            pydantic_fields = frozenset(cls.model_fields.keys())
            cls._pydantic_field_names = pydantic_fields

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

        if "pk" in kwargs:
            kwargs = config.pk.expand_pk_kwarg(kwargs=kwargs)

        # extract through fields
        through_tmp_dict = {
            field_name: kwargs.pop(field_name, None)
            for field_name in self.extract_through_names()
        }

        extra_is_ignore = cls._extra_is_ignore
        if extra_is_ignore is None:
            extra_is_ignore = config.extra == Extra.ignore
            cls._extra_is_ignore = extra_is_ignore

        if extra_is_ignore:
            allowed = cls._allowed_kwarg_names
            if allowed is None:
                allowed = frozenset(model_fields.keys()) | pydantic_fields
                cls._allowed_kwarg_names = allowed
            kwargs = {k: v for k, v in kwargs.items() if k in allowed}

        json_fields = cls._json_fields
        bytes_fields = cls._bytes_fields

        # ``relation_field_names`` is the disjoint set of fields that need
        # ``expand_relationship``; everything else can skip that call. Cached
        # on the class on first access — same pattern as ``_pydantic_field_names``.
        relation_field_names = getattr(cls, "_relation_field_names", None)
        if relation_field_names is None:
            relation_field_names = frozenset(
                name for name, f in model_fields.items() if f.is_relation
            )
            cls._relation_field_names = relation_field_names  # type: ignore[attr-defined]

        has_json = bool(json_fields)
        has_bytes = bool(bytes_fields)
        has_relations = bool(relation_field_names)

        # Validate unknown kwargs up front so the dispatch loop doesn't need
        # a per-iteration check. ``extra=ignore`` already filtered above, so
        # in that branch no unknowns can remain.
        if not extra_is_ignore:
            for k in kwargs:
                if k not in model_fields and k not in pydantic_fields:
                    try:
                        model_fields[k]
                    except KeyError as e:
                        raise ModelError(
                            f"Unknown field '{e.args[0]}' for model "
                            f"{self.get_name(lower=False)}"
                        )

        if not has_json and not has_bytes and not has_relations:
            # Fast path — plain model with no relations/json/bytes. The
            # validation pass above is the only per-key cost; the value
            # copy is a single C-level dict construction.
            return dict(kwargs), through_tmp_dict

        new_kwargs: dict[str, Any] = {}
        for k, v in kwargs.items():
            if k in relation_field_names:
                v = model_fields[k].expand_relationship(v, self, to_register=False)
            if has_json and k in json_fields:
                v = encode_json(v)
            if has_bytes and k in bytes_fields and v is not None:
                v = decode_bytes(
                    value=v,
                    represent_as_string=model_fields[k].represent_as_base64_str,
                )
            new_kwargs[k] = v
        if has_relations:
            cls.fill_shared_plain_fields(kwargs=new_kwargs)
        return new_kwargs, through_tmp_dict

    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, "_orm_persisted", False)
        object.__setattr__(self, "_orm_persisted_key", None)
        object.__setattr__(self, "__cached_hash__", None)
        object.__setattr__(self, "__setattr_fields__", set())
        object.__setattr__(self, "__json_snapshot__", None)
        object.__setattr__(
            self,
            "_orm",
            RelationsManager(
                field_map=self.extract_related_field_map(),
                owner=self,  # type: ignore[arg-type]
            ),
        )

    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:
        cached = getattr(self, "__cached_hash__", None)
        if cached is not None:
            return cached

        pk = self.pk
        cls = type(self)
        if pk is not None:
            # ``type(self)`` hashes by identity in CPython, so ``hash((pk, cls))``
            # is uniqueness-equivalent to the original ``str(pk) + cls.__name__``
            # without two string allocations per call. This is the hot path —
            # everything that goes through ``_relation_cache`` is keyed on
            # saved-pk Models.
            ret = hash((pk, cls))
        else:
            # Unsaved models can hold list/dict values in ``__dict__`` (json
            # fields, reverse-relation slots), so we still ``str(vals)`` to
            # keep the result hashable. Cold path; not perf-critical.
            related = self.extract_related_names()
            vals = {k: v for k, v in self.__dict__.items() if k not in related}
            ret = hash((str(vals), cls))

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

    def __same__(self, other: "NewBaseModel") -> bool:
        """
        Used by __eq__, compares other model to this model.

        Saved models (both with pk) compare directly by ``(pk, type)`` to
        skip the hash-cache fill on the *other* side. Unsaved/mixed states
        fall through to the original hash-equality semantics.

        :param other: model to compare to
        :type other: NewBaseModel
        :return: result of comparison
        :rtype: bool
        """
        if type(self) is not type(other):
            return False  # pragma: no cover
        self_pk = self.pk
        other_pk = other.pk
        if self_pk is not None and other_pk is not None:
            return self_pk == other_pk
        if (self_pk is None) != (other_pk is None):
            return False
        else:
            return hash(self) == other.__hash__()

    @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
        """
        if lower:
            try:
                return cls._lower_name  # type: ignore[attr-defined]
            except AttributeError:
                cls._lower_name = cls.__name__.lower()  # type: ignore[attr-defined]
                return cls._lower_name  # type: ignore[attr-defined]
        return cls.__name__

    @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 OrmarConfig"""
        return self.ormar_config.signals

    @classmethod
    def db_backend_name(cls) -> str:
        """Shortcut to database dialect,
        cause some dialect require different treatment"""
        return cls.ormar_config.database.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. A saved model matches its database row,
        so it is also marked as persisted under its current key.

        :param status: whether the model matches its database row
        :type status: bool
        """
        object.__setattr__(self, "_orm_saved", status)
        if status:
            self.set_persisted(persisted=self.pk is not None)

    def set_persisted(self, persisted: bool) -> None:
        """
        Marks whether a database row exists for the model under its current key.

        :param persisted: whether the row exists
        :type persisted: bool
        """
        object.__setattr__(self, "_orm_persisted", persisted)
        object.__setattr__(self, "_orm_persisted_key", None)

    def remember_persisted_key(self) -> None:
        """
        Called before a key field changes: keeps the key the database row is
        stored under, so ``update()``, ``delete()`` and ``load()`` still target
        that row.
        """
        if self._orm_persisted and self._orm_persisted_key is None:
            object.__setattr__(self, "_orm_persisted_key", self.pk)

    @classmethod
    def verify_writable(cls) -> None:
        """
        Refuse writes to read-only models, such as models mapped to database
        views (``OrmarConfig(view=True)``).

        :raises ReadOnlyModelError: if the model is read-only
        """
        if cls.ormar_config.view:
            raise ReadOnlyModelError(
                f"{cls.__name__} is mapped to a database view and is read-only."
            )

    def reference_dict(self) -> dict[str, Any]:
        """
        Identify the model by the values it is referenced by, used where a
        related model cannot be serialized in full (circular references): its
        primary key fields, or for a model loaded only by a unique non-pk field
        (``ForeignKey(to_field=...)``) the own fields it holds.

        :return: identifying field values by field name
        :rtype: dict[str, Any]
        """
        if self.pk is not None:
            return self.ormar_config.pk.to_dict(value=self.pk)
        own_fields = self.extract_db_own_fields()
        return {
            name: value
            for name, value in self.__dict__.items()
            if name in own_fields and value is not None
        }

    @property
    def persisted(self) -> bool:
        """
        :return: whether a database row exists for the model
        :rtype: bool
        """
        return self._orm_persisted

    @property
    def persisted_key(self) -> Any:
        """
        :return: key of the model's database row: the key it was loaded or
            last saved with, or the current key if it was not changed since
        :rtype: Any
        """
        if self._orm_persisted_key is not None:
            return self._orm_persisted_key
        return self.pk

    @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 OrmarConfig 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.ormar_config.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()
                verify_deferred_related_names(model_field=field)
                expand_reverse_relationship(model_field=field)
                update_column_definition(model=cls, field=field)
        populate_config_sqlalchemy_table_if_required(config=cls.ormar_config)
        cls.reset_column_caches()
        RelationGraph.changed()
        rebuild_primary_key(model=cls)
        rebuild_model(model=cast(type["Model"], cls))
        cls.ormar_config.requires_ref_update = False

    @classmethod
    def __get_pydantic_core_schema__(
        cls, source: Any, handler: pydantic.GetCoreSchemaHandler
    ) -> CoreSchema:
        """
        Called by pydantic whenever it generates a schema that contains the
        model: TypeAdapters (i.e. FastAPI request and response fields), other
        pydantic models or the model itself.

        Outside of ormar's own model building it first rebuilds pending models
        connected to this one, so the schema is complete. While ormar builds
        its models a pending model is embedded as its schema snapshot.

        :param source: type for which the schema is generated
        :type source: Any
        :param handler: pydantic schema handler
        :type handler: pydantic.GetCoreSchemaHandler
        :return: core schema of the model
        :rtype: CoreSchema
        """
        model = cast(type["Model"], cls)
        if not building_schemas_var.get():
            rebuild_pending_models(model=model)
        snapshot = schema_snapshot(model=model)
        return snapshot if snapshot is not None else handler(source)

    @staticmethod
    def _extract_nested_models_from_list(  # noqa: CFQ002
        relation_map: builtins.dict,
        models: MutableSequence,
        include: Union[set, builtins.dict, None],
        exclude: Union[set, builtins.dict, None],
        exclude_primary_keys: bool,
        exclude_through_models: bool,
        dump_options: DumpOptions,
        flatten_map: Optional[FlattenMap] = None,
    ) -> 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]
        :param dump_options: model_dump options forwarded to nested dumps
        :type dump_options: DumpOptions
        :param flatten_map: FlattenMap of relations to render as pk values
        :type flatten_map: Optional[FlattenMap]
        :return: list of models converted to dictionaries
        :rtype: list[dict]
        """
        result = []
        for model in models:
            try:
                model_dict = model.model_dump(
                    relation_map=relation_map,
                    include=include,
                    exclude=exclude,
                    exclude_primary_keys=exclude_primary_keys,
                    exclude_through_models=exclude_through_models,
                    flatten_fields=flatten_map,
                    **dump_options,
                )
                if not exclude_through_models:
                    model.populate_through_models(
                        model=model,
                        model_dict=model_dict,
                        include=include,
                        exclude=exclude,
                        relation_map=relation_map,
                        dump_options=dump_options,
                    )
                result.append(model_dict)
            except ReferenceError:  # pragma no cover
                continue
        return result

    @staticmethod
    def populate_through_models(
        model: "Model",
        model_dict: builtins.dict,
        include: Union[set, builtins.dict],
        exclude: Union[set, builtins.dict],
        relation_map: builtins.dict,
        dump_options: DumpOptions,
    ) -> None:
        """
        Populates through models with values from dict representation.

        :param model: model to populate through models
        :type model: Model
        :param model_dict: dict representation of the model
        :type model_dict: dict
        :param include: fields to include
        :type include: dict
        :param exclude: fields to exclude
        :type exclude: dict
        :param relation_map: map of relations to follow to avoid circular refs
        :type relation_map: dict
        :param dump_options: model_dump options forwarded to the through model dump
        :type dump_options: DumpOptions
        :return: None
        :rtype: None
        """

        models_to_populate = filter_not_excluded_fields(
            fields=model.extract_through_names(),
            include=normalize_to_dict(include),
            exclude=normalize_to_dict(exclude),
        )
        through_fields_to_populate = [
            model.ormar_config.model_fields[through_model]
            for through_model in models_to_populate
            if model.ormar_config.model_fields[through_model].related_name
            not in relation_map
        ]
        for through_field in through_fields_to_populate:
            through_instance = getattr(model, through_field.name)
            if through_instance:
                model_dict[through_field.name] = through_instance.model_dump(
                    **dump_options
                )

    @staticmethod
    def _resolve_field_descent(  # noqa: CFQ002
        field: str,
        relation_field: ForeignKeyField,
        nested_model: Union["Model", MutableSequence["Model"]],
        flatten_map: Optional[FlattenMap],
        relation_map: builtins.dict,
        include: Optional[builtins.dict],
        exclude: Optional[builtins.dict],
        dict_instance: builtins.dict,
        dump_options: DumpOptions,
    ) -> Optional[NestedDescent]:
        """
        Decide how to dump a related field. When the field is flattened, write
        its primary-key representation directly into ``dict_instance`` and
        return ``None`` so the caller skips further descent. When the field is
        an excluded list, also return ``None``. Otherwise return a
        ``NestedDescent`` carrying the per-field locals the caller threads
        into the recursive dump.

        :param field: relation field name being processed
        :type field: str
        :param relation_field: the relation field being processed
        :type relation_field: ForeignKeyField
        :param nested_model: value of the relation on the current instance,
            null relations are handled by the caller
        :type nested_model: Union[Model, MutableSequence[Model]]
        :param flatten_map: current flatten directive scope, or ``None``
        :type flatten_map: Optional[FlattenMap]
        :param relation_map: relation traversal map for the current scope
        :type relation_map: dict
        :param include: include selector for the current scope
        :type include: Optional[dict]
        :param exclude: exclude selector for the current scope
        :type exclude: Optional[dict]
        :param dict_instance: dict being built for the current model
        :type dict_instance: dict
        :param dump_options: model_dump options; ``exclude_list`` skips list
            relations and ``mode`` is applied to flattened primary-key values
        :type dump_options: DumpOptions
        :return: per-field locals, or ``None`` if the field was handled inline
            (flattened or skipped)
        :rtype: Optional[NestedDescent]
        """
        if isinstance(nested_model, MutableSequence) and dump_options["exclude_list"]:
            return None
        if flatten_map is not None and flatten_map.is_field_flattened(field):
            value = (
                [relation_field.flat_value(related=m) for m in nested_model]
                if isinstance(nested_model, MutableSequence)
                else relation_field.flat_value(related=nested_model)
            )
            if dump_options["mode"] == "json":
                value = to_jsonable_python(value)
            dict_instance[field] = value
            return None
        return NestedDescent(
            flatten_map=flatten_map.descend(field) if flatten_map is not None else None,
            relation_map=cast(
                builtins.dict, skip_ellipsis(relation_map, field, default=dict())
            ),
            include=convert_all(skip_ellipsis(include, field)),
            exclude=convert_all(skip_ellipsis(exclude, field)),
        )

    def _extract_nested_models(  # noqa: CCR001, CFQ002
        self,
        relation_map: builtins.dict,
        dict_instance: builtins.dict,
        include: Optional[builtins.dict],
        exclude: Optional[builtins.dict],
        exclude_primary_keys: bool,
        exclude_through_models: bool,
        dump_options: DumpOptions,
        flatten_map: Optional[FlattenMap] = None,
    ) -> builtins.dict:
        """
        Traverse nested models and converts them into dictionaries.
        Calls itself recursively if needed.

        :param relation_map: map of the relations to follow to avoid circular deps
        :type relation_map: dict
        :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 dump_options: model_dump options forwarded to nested dumps
        :type dump_options: DumpOptions
        :param flatten_map: FlattenMap directing relations to render as pk values
        :type flatten_map: Optional[FlattenMap]
        :return: current model dict with child models converted to dictionaries
        :rtype: dict
        """
        fields = filter_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 nested_model is None:
                    if not self._is_null_relation_excluded(field, dump_options):
                        dict_instance[field] = None
                    continue
                descent = self._resolve_field_descent(
                    field=field,
                    relation_field=cast(
                        ForeignKeyField, self.ormar_config.model_fields[field]
                    ),
                    nested_model=nested_model,
                    flatten_map=flatten_map,
                    relation_map=relation_map,
                    include=include,
                    exclude=exclude,
                    dict_instance=dict_instance,
                    dump_options=dump_options,
                )
                if descent is None:
                    continue
                if isinstance(nested_model, MutableSequence):
                    dict_instance[field] = self._extract_nested_models_from_list(
                        relation_map=descent.relation_map,
                        models=nested_model,
                        include=descent.include,
                        exclude=descent.exclude,
                        exclude_primary_keys=exclude_primary_keys,
                        exclude_through_models=exclude_through_models,
                        flatten_map=descent.flatten_map,
                        dump_options=dump_options,
                    )
                else:
                    model_dict = nested_model.model_dump(
                        relation_map=descent.relation_map,
                        include=descent.include,
                        exclude=descent.exclude,
                        exclude_primary_keys=exclude_primary_keys,
                        exclude_through_models=exclude_through_models,
                        flatten_fields=descent.flatten_map,
                        **dump_options,
                    )
                    if not exclude_through_models:
                        nested_model.populate_through_models(
                            model=nested_model,
                            model_dict=model_dict,
                            include=descent.include,
                            exclude=descent.exclude,
                            relation_map=descent.relation_map,
                            dump_options=dump_options,
                        )
                    dict_instance[field] = model_dict
            except ReferenceError:  # pragma: no cover
                if not self._is_null_relation_excluded(field, dump_options):
                    dict_instance[field] = None
        return dict_instance

    def _is_null_relation_excluded(self, field: str, dump_options: DumpOptions) -> bool:
        """
        Check if a relation without a value should be left out of the dump.
        Relation fields cannot declare a default, so a null relation always
        equals its default and is excluded by ``exclude_none``,
        ``exclude_defaults`` and, when it was never set explicitly,
        by ``exclude_unset``.

        :param field: name of the relation field
        :type field: str
        :param dump_options: model_dump options of the current dump
        :type dump_options: DumpOptions
        :return: True if the null relation should be skipped
        :rtype: bool
        """
        return (
            dump_options["exclude_none"]
            or dump_options["exclude_defaults"]
            or (dump_options["exclude_unset"] and field not in self.model_fields_set)
        )

    @typing_extensions.deprecated(
        "The `dict` method is deprecated; use `model_dump` instead.",
        category=OrmarDeprecatedSince020,
    )
    def dict(  # type: ignore # noqa A003
        self,
        *,
        include: Union[set, builtins.dict, None] = None,
        exclude: Union[set, builtins.dict, None] = None,
        by_alias: bool = False,
        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: Optional[builtins.dict] = None,
    ) -> "DictStrAny":  # noqa: A003 # pragma: no cover
        warnings.warn(
            "The `dict` method is deprecated; use `model_dump` instead.",
            DeprecationWarning,
        )
        return self.model_dump(
            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,
            exclude_list=exclude_list,
            relation_map=relation_map,
        )

    def model_dump(  # type: ignore # noqa A003, CFQ002
        self,
        *,
        mode: Union[Literal["json", "python"], str] = "python",
        include: Union[set, builtins.dict, None] = None,
        exclude: Union[set, builtins.dict, None] = None,
        by_alias: bool = False,
        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: Optional[builtins.dict] = None,
        flatten_fields: Union[
            set, list, str, tuple, builtins.dict, "FieldAccessor", FlattenMap, None
        ] = None,
        flatten_all: bool = False,
        round_trip: bool = False,
        warnings: bool = True,
    ) -> "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 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 circular deps
        :type relation_map: dict
        :param flatten_fields: relations to render as their primary-key value.
            Accepts dunder-strings, list/set/tuple, nested dict (with Ellipsis),
            or ``FieldAccessor`` / list of accessors. Resolves to a nested-dict
            spec used during traversal.
        :type flatten_fields: Union[set, list, str, tuple, dict, FieldAccessor, None]
        :param flatten_all: if True every nested relation is collapsed to its pk
        :type flatten_all: bool
        :param mode: The mode in which `to_python` should run.
            If mode is 'json', the dictionary will only contain JSON serializable types.
            If mode is 'python', the dictionary may contain any Python objects.
        :type mode: str
        :param round_trip: flag to enable serialization round-trip support
        :type round_trip: bool
        :param warnings: flag to log warnings for invalid fields
        :type warnings: bool
        :return:
        :rtype:
        """
        flatten_map = self._resolve_flatten_map(
            flatten_fields=flatten_fields, flatten_all=flatten_all
        )
        if exclude_primary_keys and flatten_map:
            raise QueryDefinitionError(
                "flatten_fields / flatten_all cannot be combined with "
                "exclude_primary_keys=True: flattening renders primary keys, "
                "excluding removes them."
            )
        include_dict = normalize_to_dict(include)
        exclude_dict = normalize_to_dict(exclude)
        if flatten_map is not None:
            flatten_map.check_vs_selector(include_dict, "include")
            flatten_map.check_vs_selector(exclude_dict, "exclude")

        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().model_dump(
            mode=mode,
            include=include,
            exclude=pydantic_exclude,
            by_alias=by_alias,
            exclude_defaults=exclude_defaults,
            exclude_unset=exclude_unset,
            exclude_none=exclude_none,
            round_trip=round_trip,
            warnings=False,
        )

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

        relation_map = (
            relation_map
            if relation_map is not None
            else cast(builtins.dict, self._default_relation_map())
        )
        if relation_map and getattr(self, "__pk_only__", False):
            # a key-only model holds no relations besides the ones in its key
            key_relations = self.ormar_config.pk.relation_parts
            relation_map = {
                name: nested
                for name, nested in relation_map.items()
                if name in key_relations
            }
        if relation_map:
            dict_instance = self._extract_nested_models(
                relation_map=relation_map,
                dict_instance=dict_instance,
                include=include_dict,
                exclude=exclude_dict,
                exclude_primary_keys=exclude_primary_keys,
                exclude_through_models=exclude_through_models,
                flatten_map=flatten_map,
                dump_options=DumpOptions(
                    mode=mode,
                    by_alias=by_alias,
                    exclude_unset=exclude_unset,
                    exclude_defaults=exclude_defaults,
                    exclude_none=exclude_none,
                    exclude_list=exclude_list,
                    round_trip=round_trip,
                ),
            )

        return dict_instance

    def _resolve_flatten_map(
        self,
        flatten_fields: Union[
            set, list, str, tuple, builtins.dict, "FieldAccessor", FlattenMap, None
        ],
        flatten_all: bool,
    ) -> Optional[FlattenMap]:
        """
        Produce a :class:`FlattenMap` from the various input forms accepted by
        ``model_dump``. Resolves dunder strings / lists / sets / nested dicts /
        ``FieldAccessor`` chains; an already-resolved ``FlattenMap`` (passed
        during recursion) is returned as-is.

        :param flatten_fields: user spec, nested dict, or FlattenMap from recursion
        :type flatten_fields: Union[set, list, str, tuple, dict, FieldAccessor,
            FlattenMap, None]
        :param flatten_all: if True every relation flattens regardless of spec
        :type flatten_all: bool
        :return: resolved FlattenMap, or None when nothing should flatten
        :rtype: Optional[FlattenMap]
        """
        if flatten_fields is None and not flatten_all:
            excludable = getattr(self, "__ormar_excludable__", None)
            return excludable.flatten_map() if excludable is not None else None
        return resolve_flatten_map(
            model_cls=cast(type["Model"], type(self)),
            flatten_fields=flatten_fields,
            flatten_all=flatten_all,
        )

    @typing_extensions.deprecated(
        "The `json` method is deprecated; use `model_dump_json` instead.",
        category=OrmarDeprecatedSince020,
    )
    def json(  # type: ignore # noqa A003
        self,
        *,
        include: Union[set, builtins.dict, None] = None,
        exclude: Union[set, builtins.dict, None] = None,
        by_alias: bool = False,
        exclude_unset: bool = False,
        exclude_defaults: bool = False,
        exclude_none: bool = False,
        exclude_primary_keys: bool = False,
        exclude_through_models: bool = False,
        **dumps_kwargs: Any,
    ) -> str:  # pragma: no cover
        warnings.warn(
            "The `json` method is deprecated; use `model_dump_json` instead.",
            DeprecationWarning,
        )
        return self.model_dump_json(
            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,
            **dumps_kwargs,
        )

    def model_dump_json(  # type: ignore # noqa A003
        self,
        *,
        include: Union[set, builtins.dict, None] = None,
        exclude: Union[set, builtins.dict, None] = None,
        by_alias: bool = False,
        exclude_unset: bool = False,
        exclude_defaults: bool = False,
        exclude_none: bool = False,
        exclude_primary_keys: bool = False,
        exclude_through_models: bool = False,
        flatten_fields: Union[
            set, list, str, tuple, builtins.dict, "FieldAccessor", FlattenMap, None
        ] = None,
        flatten_all: 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()`.
        """
        data = self.model_dump(
            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,
            flatten_fields=flatten_fields,
            flatten_all=flatten_all,
        )
        return self.__pydantic_serializer__.to_json(data, warnings=False).decode()

    @classmethod
    @typing_extensions.deprecated(
        "The `construct` method is deprecated; use `model_construct` instead.",
        category=OrmarDeprecatedSince020,
    )
    def construct(
        cls: type["T"], _fields_set: Union[set[str], None] = None, **values: Any
    ) -> "T":  # pragma: no cover
        warnings.warn(
            "The `construct` method is deprecated; use `model_construct` instead.",
            DeprecationWarning,
        )
        return cls.model_construct(_fields_set=_fields_set, **values)

    @classmethod
    def model_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.model_fields.items():
            if name in own_values:
                fields_values[name] = own_values[name]
            elif not field.is_required():
                fields_values[name] = field.get_default()
        fields_values.update(own_values)

        if _fields_set is None:
            _fields_set = set(values.keys())

        extra_allowed = cls.model_config.get("extra") == "allow"
        if not extra_allowed:
            fields_values.update(values)
        object.__setattr__(model, "__dict__", fields_values)
        model._initialize_internal_attributes()
        cls._construct_relations(model=model, values=values)
        object.__setattr__(model, "__pydantic_fields_set__", _fields_set)
        return cls._pydantic_model_construct_finalizer(
            model=model, extra_allowed=extra_allowed, values=values
        )

    @classmethod
    def _pydantic_model_construct_finalizer(
        cls: type["T"], model: "T", extra_allowed: bool, **values: Any
    ) -> "T":
        """
        Recreate pydantic model_construct logic here as we do not call super method.
        """
        _extra: Union[builtins.dict[str, Any], None] = None
        if extra_allowed:  # pragma: no cover
            _extra = {}
            for k, v in values.items():
                _extra[k] = v

        if not cls.__pydantic_root_model__:
            object.__setattr__(model, "__pydantic_extra__", _extra)

        if cls.__pydantic_post_init__:  # pragma: no cover
            model.model_post_init(None)
        elif not cls.__pydantic_root_model__:
            # Note: if there are any private attributes,
            # cls.__pydantic_post_init__ would exist
            # Since it doesn't, that means that `__pydantic_private__`
            # should be set to None
            object.__setattr__(model, "__pydantic_private__", None)

        return model

    @classmethod
    def _construct_relations(cls: type["T"], model: "T", values: builtins.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.ormar_config.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: builtins.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_bytes_to_str(
        self, column_name: str, value: Any
    ) -> Union[str, builtins.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.ormar_config.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 _extract_own_model_fields(self) -> builtins.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) -> builtins.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
        """
        self_fields = self._extract_own_model_fields()
        self_fields = {
            k: v
            for k, v in self_fields.items()
            if self.get_column_alias(field_name=k) in self.ormar_config.table.columns
        }
        relation_values: dict[str, dict[str, Any]] = {}
        for field in self._extract_db_related_names():
            relation_field = cast(
                "ForeignKeyField", self.ormar_config.model_fields[field]
            )
            related = getattr(self, field)
            values = relation_field.link.values_for(related=related)
            if None in values.values() and (
                related is not None or not relation_field.nullable
            ):
                raise ModelPersistenceError(
                    f"You cannot save {relation_field.to.get_name()} "
                    f"model without {', '.join(relation_field.target_fields())} set!"
                )
            relation_values[field] = values
        self.merge_relation_values(target=self_fields, relation_values=relation_values)
        return self_fields

persisted property

Returns:

Type Description
bool

whether a database row exists for the model

persisted_key property

Returns:

Type Description
Any

key of the model's database row: the key it was loaded or last saved with, or the current key if it was not changed since

saved property

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

signals property

Exposes signals from model OrmarConfig

__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
Python
800
801
802
803
804
805
806
807
808
809
810
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

__get_pydantic_core_schema__(source, handler) classmethod

Called by pydantic whenever it generates a schema that contains the model: TypeAdapters (i.e. FastAPI request and response fields), other pydantic models or the model itself.

Outside of ormar's own model building it first rebuilds pending models connected to this one, so the schema is complete. While ormar builds its models a pending model is embedded as its schema snapshot.

Parameters:

Name Type Description Default
source Any

type for which the schema is generated

required
handler GetCoreSchemaHandler

pydantic schema handler

required

Returns:

Type Description
CoreSchema

core schema of the model

Source code in ormar/models/newbasemodel.py
Python
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
@classmethod
def __get_pydantic_core_schema__(
    cls, source: Any, handler: pydantic.GetCoreSchemaHandler
) -> CoreSchema:
    """
    Called by pydantic whenever it generates a schema that contains the
    model: TypeAdapters (i.e. FastAPI request and response fields), other
    pydantic models or the model itself.

    Outside of ormar's own model building it first rebuilds pending models
    connected to this one, so the schema is complete. While ormar builds
    its models a pending model is embedded as its schema snapshot.

    :param source: type for which the schema is generated
    :type source: Any
    :param handler: pydantic schema handler
    :type handler: pydantic.GetCoreSchemaHandler
    :return: core schema of the model
    :rtype: CoreSchema
    """
    model = cast(type["Model"], cls)
    if not building_schemas_var.get():
        rebuild_pending_models(model=model)
    snapshot = schema_snapshot(model=model)
    return snapshot if snapshot is not None else handler(source)

__getattr__(item)

Used for private attributes of pydantic v2.

Parameters:

Name Type Description Default
item str

name of attribute

required

Returns:

Type Description
Any

Any

Source code in ormar/models/newbasemodel.py
Python
534
535
536
537
538
539
540
541
542
543
544
545
546
def __getattr__(self, item: str) -> Any:
    """
    Used for private attributes of pydantic v2.

    :param item: name of attribute
    :type item: str
    :return: Any
    :rtype: Any
    """
    # TODO: Check __pydantic_extra__
    if item == "__pydantic_extra__":
        return None
    return super().__getattr__(item)  # type: ignore

__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 OrmarConfig cannot be initialized.

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
Python
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
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 OrmarConfig cannot be initialized.

    :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()

    object.__setattr__(self, "__pk_only__", False)
    object.__setattr__(self, "__ormar_excludable__", None)

    new_kwargs, through_tmp_dict = self._process_kwargs(kwargs)

    decoded = (
        self.serialize_nested_models_json_fields(kwargs=new_kwargs)
        if self.extract_related_fields()
        else []
    )
    try:
        self.__pydantic_validator__.validate_python(
            new_kwargs,
            self_instance=self,  # type: ignore
        )
    finally:
        self.restore_nested_models_json_fields(decoded=decoded)
    self._register_related_models(new_kwargs, through_tmp_dict)

__same__(other)

Used by eq, compares other model to this model.

Saved models (both with pk) compare directly by (pk, type) to skip the hash-cache fill on the other side. Unsaved/mixed states fall through to the original hash-equality semantics.

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
Python
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
def __same__(self, other: "NewBaseModel") -> bool:
    """
    Used by __eq__, compares other model to this model.

    Saved models (both with pk) compare directly by ``(pk, type)`` to
    skip the hash-cache fill on the *other* side. Unsaved/mixed states
    fall through to the original hash-equality semantics.

    :param other: model to compare to
    :type other: NewBaseModel
    :return: result of comparison
    :rtype: bool
    """
    if type(self) is not type(other):
        return False  # pragma: no cover
    self_pk = self.pk
    other_pk = other.pk
    if self_pk is not None and other_pk is not None:
        return self_pk == other_pk
    if (self_pk is None) != (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
Python
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
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 name in self.ormar_config.pk.fields:
        self.remember_persisted_key()

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

    if name in self.ormar_config.model_fields:
        self.__setattr_fields__.add(name)

    # In this case, the hash could have changed, so update it
    if name in self.ormar_config.pk.fields 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
Python
889
890
891
892
893
@classmethod
def db_backend_name(cls) -> str:
    """Shortcut to database dialect,
    cause some dialect require different treatment"""
    return cls.ormar_config.database.dialect.name

flat_row_model() classmethod

Return whether the model has trusted_row_construction(), no relations at all and no custom serialization (serializers or an overridden model_dump), so its rows and its model_dump() hold plain column values only.

For such models bulk_create copies each instance's __dict__ instead of calling model_dump() (see dump_for_save).

Returns:

Type Description
bool

True for trusted models without relations

Source code in ormar/models/newbasemodel.py
Python
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
@classmethod
def flat_row_model(cls) -> bool:
    """
    Return whether the model has ``trusted_row_construction()``, no
    relations at all and no custom serialization (serializers or an
    overridden ``model_dump``), so its rows and its ``model_dump()`` hold
    plain column values only.

    For such models ``bulk_create`` copies each instance's ``__dict__``
    instead of calling ``model_dump()`` (see ``dump_for_save``).

    :return: True for trusted models without relations
    :rtype: bool
    """
    decorators = cls.__pydantic_decorators__
    return (
        cls.trusted_row_construction()
        and not cls._row_relation_names
        and not decorators.field_serializers
        and not decorators.model_serializers
        and cls.model_dump is NewBaseModel.model_dump
    )

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
Python
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
@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
    """
    if lower:
        try:
            return cls._lower_name  # type: ignore[attr-defined]
        except AttributeError:
            cls._lower_name = cls.__name__.lower()  # type: ignore[attr-defined]
            return cls._lower_name  # type: ignore[attr-defined]
    return cls.__name__

model_dump(*, mode='python', include=None, exclude=None, by_alias=False, exclude_unset=False, exclude_defaults=False, exclude_none=False, exclude_primary_keys=False, exclude_through_models=False, exclude_list=False, relation_map=None, flatten_fields=None, flatten_all=False, round_trip=False, warnings=True)

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, None]

fields to include

None
exclude Union[set, dict, None]

fields to exclude

None
by_alias bool

flag to get values by alias - passed to pydantic

False
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 Optional[dict]

map of the relations to follow to avoid circular deps

None
flatten_fields Union[set, list, str, tuple, dict, FieldAccessor, FlattenMap, None]

relations to render as their primary-key value. Accepts dunder-strings, list/set/tuple, nested dict (with Ellipsis), or FieldAccessor / list of accessors. Resolves to a nested-dict spec used during traversal.

None
flatten_all bool

if True every nested relation is collapsed to its pk

False
mode Union[Literal['json', 'python'], str]

The mode in which to_python should run. If mode is 'json', the dictionary will only contain JSON serializable types. If mode is 'python', the dictionary may contain any Python objects.

'python'
round_trip bool

flag to enable serialization round-trip support

False
warnings bool

flag to log warnings for invalid fields

True

Returns:

Type Description
Source code in ormar/models/newbasemodel.py
Python
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
def model_dump(  # type: ignore # noqa A003, CFQ002
    self,
    *,
    mode: Union[Literal["json", "python"], str] = "python",
    include: Union[set, builtins.dict, None] = None,
    exclude: Union[set, builtins.dict, None] = None,
    by_alias: bool = False,
    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: Optional[builtins.dict] = None,
    flatten_fields: Union[
        set, list, str, tuple, builtins.dict, "FieldAccessor", FlattenMap, None
    ] = None,
    flatten_all: bool = False,
    round_trip: bool = False,
    warnings: bool = True,
) -> "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 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 circular deps
    :type relation_map: dict
    :param flatten_fields: relations to render as their primary-key value.
        Accepts dunder-strings, list/set/tuple, nested dict (with Ellipsis),
        or ``FieldAccessor`` / list of accessors. Resolves to a nested-dict
        spec used during traversal.
    :type flatten_fields: Union[set, list, str, tuple, dict, FieldAccessor, None]
    :param flatten_all: if True every nested relation is collapsed to its pk
    :type flatten_all: bool
    :param mode: The mode in which `to_python` should run.
        If mode is 'json', the dictionary will only contain JSON serializable types.
        If mode is 'python', the dictionary may contain any Python objects.
    :type mode: str
    :param round_trip: flag to enable serialization round-trip support
    :type round_trip: bool
    :param warnings: flag to log warnings for invalid fields
    :type warnings: bool
    :return:
    :rtype:
    """
    flatten_map = self._resolve_flatten_map(
        flatten_fields=flatten_fields, flatten_all=flatten_all
    )
    if exclude_primary_keys and flatten_map:
        raise QueryDefinitionError(
            "flatten_fields / flatten_all cannot be combined with "
            "exclude_primary_keys=True: flattening renders primary keys, "
            "excluding removes them."
        )
    include_dict = normalize_to_dict(include)
    exclude_dict = normalize_to_dict(exclude)
    if flatten_map is not None:
        flatten_map.check_vs_selector(include_dict, "include")
        flatten_map.check_vs_selector(exclude_dict, "exclude")

    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().model_dump(
        mode=mode,
        include=include,
        exclude=pydantic_exclude,
        by_alias=by_alias,
        exclude_defaults=exclude_defaults,
        exclude_unset=exclude_unset,
        exclude_none=exclude_none,
        round_trip=round_trip,
        warnings=False,
    )

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

    relation_map = (
        relation_map
        if relation_map is not None
        else cast(builtins.dict, self._default_relation_map())
    )
    if relation_map and getattr(self, "__pk_only__", False):
        # a key-only model holds no relations besides the ones in its key
        key_relations = self.ormar_config.pk.relation_parts
        relation_map = {
            name: nested
            for name, nested in relation_map.items()
            if name in key_relations
        }
    if relation_map:
        dict_instance = self._extract_nested_models(
            relation_map=relation_map,
            dict_instance=dict_instance,
            include=include_dict,
            exclude=exclude_dict,
            exclude_primary_keys=exclude_primary_keys,
            exclude_through_models=exclude_through_models,
            flatten_map=flatten_map,
            dump_options=DumpOptions(
                mode=mode,
                by_alias=by_alias,
                exclude_unset=exclude_unset,
                exclude_defaults=exclude_defaults,
                exclude_none=exclude_none,
                exclude_list=exclude_list,
                round_trip=round_trip,
            ),
        )

    return dict_instance

model_dump_json(*, include=None, exclude=None, by_alias=False, exclude_unset=False, exclude_defaults=False, exclude_none=False, exclude_primary_keys=False, exclude_through_models=False, flatten_fields=None, flatten_all=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
Python
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
def model_dump_json(  # type: ignore # noqa A003
    self,
    *,
    include: Union[set, builtins.dict, None] = None,
    exclude: Union[set, builtins.dict, None] = None,
    by_alias: bool = False,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    exclude_primary_keys: bool = False,
    exclude_through_models: bool = False,
    flatten_fields: Union[
        set, list, str, tuple, builtins.dict, "FieldAccessor", FlattenMap, None
    ] = None,
    flatten_all: 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()`.
    """
    data = self.model_dump(
        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,
        flatten_fields=flatten_fields,
        flatten_all=flatten_all,
    )
    return self.__pydantic_serializer__.to_json(data, warnings=False).decode()

populate_through_models(model, model_dict, include, exclude, relation_map, dump_options) staticmethod

Populates through models with values from dict representation.

Parameters:

Name Type Description Default
model Model

model to populate through models

required
model_dict dict

dict representation of the model

required
include Union[set, dict]

fields to include

required
exclude Union[set, dict]

fields to exclude

required
relation_map dict

map of relations to follow to avoid circular refs

required
dump_options DumpOptions

model_dump options forwarded to the through model dump

required

Returns:

Type Description
None

None

Source code in ormar/models/newbasemodel.py
Python
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
@staticmethod
def populate_through_models(
    model: "Model",
    model_dict: builtins.dict,
    include: Union[set, builtins.dict],
    exclude: Union[set, builtins.dict],
    relation_map: builtins.dict,
    dump_options: DumpOptions,
) -> None:
    """
    Populates through models with values from dict representation.

    :param model: model to populate through models
    :type model: Model
    :param model_dict: dict representation of the model
    :type model_dict: dict
    :param include: fields to include
    :type include: dict
    :param exclude: fields to exclude
    :type exclude: dict
    :param relation_map: map of relations to follow to avoid circular refs
    :type relation_map: dict
    :param dump_options: model_dump options forwarded to the through model dump
    :type dump_options: DumpOptions
    :return: None
    :rtype: None
    """

    models_to_populate = filter_not_excluded_fields(
        fields=model.extract_through_names(),
        include=normalize_to_dict(include),
        exclude=normalize_to_dict(exclude),
    )
    through_fields_to_populate = [
        model.ormar_config.model_fields[through_model]
        for through_model in models_to_populate
        if model.ormar_config.model_fields[through_model].related_name
        not in relation_map
    ]
    for through_field in through_fields_to_populate:
        through_instance = getattr(model, through_field.name)
        if through_instance:
            model_dict[through_field.name] = through_instance.model_dump(
                **dump_options
            )

reference_dict()

Identify the model by the values it is referenced by, used where a related model cannot be serialized in full (circular references): its primary key fields, or for a model loaded only by a unique non-pk field (ForeignKey(to_field=...)) the own fields it holds.

Returns:

Type Description
dict[str, Any]

identifying field values by field name

Source code in ormar/models/newbasemodel.py
Python
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
def reference_dict(self) -> dict[str, Any]:
    """
    Identify the model by the values it is referenced by, used where a
    related model cannot be serialized in full (circular references): its
    primary key fields, or for a model loaded only by a unique non-pk field
    (``ForeignKey(to_field=...)``) the own fields it holds.

    :return: identifying field values by field name
    :rtype: dict[str, Any]
    """
    if self.pk is not None:
        return self.ormar_config.pk.to_dict(value=self.pk)
    own_fields = self.extract_db_own_fields()
    return {
        name: value
        for name, value in self.__dict__.items()
        if name in own_fields and value is not None
    }

remember_persisted_key()

Called before a key field changes: keeps the key the database row is stored under, so update(), delete() and load() still target that row.

Source code in ormar/models/newbasemodel.py
Python
921
922
923
924
925
926
927
928
def remember_persisted_key(self) -> None:
    """
    Called before a key field changes: keeps the key the database row is
    stored under, so ``update()``, ``delete()`` and ``load()`` still target
    that row.
    """
    if self._orm_persisted and self._orm_persisted_key is None:
        object.__setattr__(self, "_orm_persisted_key", self.pk)

remove(parent, name)

Removes child from relation with given name in RelationshipManager

Source code in ormar/models/newbasemodel.py
Python
895
896
897
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_persisted(persisted)

Marks whether a database row exists for the model under its current key.

Parameters:

Name Type Description Default
persisted bool

whether the row exists

required
Source code in ormar/models/newbasemodel.py
Python
911
912
913
914
915
916
917
918
919
def set_persisted(self, persisted: bool) -> None:
    """
    Marks whether a database row exists for the model under its current key.

    :param persisted: whether the row exists
    :type persisted: bool
    """
    object.__setattr__(self, "_orm_persisted", persisted)
    object.__setattr__(self, "_orm_persisted_key", None)

set_save_status(status)

Sets value of the save status. A saved model matches its database row, so it is also marked as persisted under its current key.

Parameters:

Name Type Description Default
status bool

whether the model matches its database row

required
Source code in ormar/models/newbasemodel.py
Python
899
900
901
902
903
904
905
906
907
908
909
def set_save_status(self, status: bool) -> None:
    """
    Sets value of the save status. A saved model matches its database row,
    so it is also marked as persisted under its current key.

    :param status: whether the model matches its database row
    :type status: bool
    """
    object.__setattr__(self, "_orm_saved", status)
    if status:
        self.set_persisted(persisted=self.pk is not None)

trusted_row_construction() classmethod

Return whether rows of this model can be turned into instances without running __init__.

A database row is already converted by the column types (an Integer column returns int, a DateTime one datetime), so pydantic's validation would hand back the same values. Skipping it is only safe when nothing on the model could change a value or has side effects, so the model must have none of:

  • through fields or a custom __init__
  • validators of any kind, private attributes or model_post_init
  • extra fields (extra="allow")
  • fields whose pydantic type differs from the column type, encrypted fields or fields represented as base64 strings
  • value-changing model config (VALUE_CHANGING_CONFIG: enum values, string transformations, number coercion, strict mode)

Computed once per class, together with the per-class lookups the trusted path uses (required fields, relation names and field order). Defining a related model later resets it (see reset_relation_caches)::

Text Only
1
2
3
4
5
6
7
8
class Author(ormar.Model):
    ormar_config = base_ormar_config.copy(tablename="authors")

    id: int = ormar.Integer(primary_key=True)
    name: str = ormar.String(max_length=100)


Author.trusted_row_construction()  # -> True

Returns:

Type Description
bool

True when database rows can be trusted as field values

Source code in ormar/models/newbasemodel.py
Python
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
@classmethod
def trusted_row_construction(cls) -> bool:
    """
    Return whether rows of this model can be turned into instances without
    running ``__init__``.

    A database row is already converted by the column types (an Integer
    column returns ``int``, a DateTime one ``datetime``), so pydantic's
    validation would hand back the same values. Skipping it is only safe
    when nothing on the model could change a value or has side effects,
    so the model must have none of:

    - through fields or a custom ``__init__``
    - validators of any kind, private attributes or ``model_post_init``
    - extra fields (``extra="allow"``)
    - fields whose pydantic type differs from the column type, encrypted
      fields or fields represented as base64 strings
    - value-changing model config (``VALUE_CHANGING_CONFIG``: enum values,
      string transformations, number coercion, strict mode)

    Computed once per class, together with the per-class lookups the
    trusted path uses (required fields, relation names and field order).
    Defining a related model later resets it (see
    ``reset_relation_caches``)::

        class Author(ormar.Model):
            ormar_config = base_ormar_config.copy(tablename="authors")

            id: int = ormar.Integer(primary_key=True)
            name: str = ormar.String(max_length=100)


        Author.trusted_row_construction()  # -> True

    :return: True when database rows can be trusted as field values
    :rtype: bool
    """
    cached = cls.__dict__.get("_trusted_rows")
    if cached is not None:
        return cast(bool, cached)
    decorators = cls.__pydantic_decorators__
    model_fields = cls.ormar_config.model_fields
    trusted = (
        cls.__init__ is NewBaseModel.__init__
        and not cls.extract_through_names()
        and set(cls.model_fields) == set(model_fields)
        and all(
            (field.is_relation or field.__pydantic_type__ is field.__type__)
            and not field.encrypt_secret
            and not field.represent_as_base64_str
            for field in model_fields.values()
        )
        and not (
            decorators.validators
            or decorators.field_validators
            or decorators.root_validators
            or decorators.model_validators
        )
        and not cls.__private_attributes__
        and cls.__pydantic_post_init__ is None
        and cls.model_config.get("extra") != "allow"
        and not any(cls.model_config.get(key) for key in VALUE_CHANGING_CONFIG)
    )
    type.__setattr__(
        cls,
        "_required_row_fields",
        frozenset(
            name for name, info in cls.model_fields.items() if info.is_required()
        ),
    )
    type.__setattr__(cls, "_row_relation_names", tuple(cls.extract_related_names()))
    type.__setattr__(cls, "_row_field_order", tuple(cls.model_fields))
    type.__setattr__(cls, "_trusted_rows", trusted)
    return trusted

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 OrmarConfig 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
Python
 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
@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 OrmarConfig 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.ormar_config.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()
            verify_deferred_related_names(model_field=field)
            expand_reverse_relationship(model_field=field)
            update_column_definition(model=cls, field=field)
    populate_config_sqlalchemy_table_if_required(config=cls.ormar_config)
    cls.reset_column_caches()
    RelationGraph.changed()
    rebuild_primary_key(model=cls)
    rebuild_model(model=cast(type["Model"], cls))
    cls.ormar_config.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
Python
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
def update_from_dict(self, value_dict: builtins.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

verify_writable() classmethod

Refuse writes to read-only models, such as models mapped to database views (OrmarConfig(view=True)).

Raises:

Type Description
ReadOnlyModelError

if the model is read-only

Source code in ormar/models/newbasemodel.py
Python
930
931
932
933
934
935
936
937
938
939
940
941
@classmethod
def verify_writable(cls) -> None:
    """
    Refuse writes to read-only models, such as models mapped to database
    views (``OrmarConfig(view=True)``).

    :raises ReadOnlyModelError: if the model is read-only
    """
    if cls.ormar_config.view:
        raise ReadOnlyModelError(
            f"{cls.__name__} is mapped to a database view and is read-only."
        )