Skip to content

newbasemodel

NewBaseModel

Bases: pydantic.BaseModel, ModelTableProxy

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

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

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

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

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

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

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

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

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

        Json fields are automatically loaded/dumped if needed.

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

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

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

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

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

        new_kwargs, through_tmp_dict = self._process_kwargs(kwargs)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        Removes property_fields

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

        Nullifies fields that should be excluded.

        Extracts through models from kwargs into temporary dict.

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

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

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

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

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

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

        return new_kwargs, through_tmp_dict

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        Sets self_reference flag on models that links to themselves.

        Calls the pydantic method to evaluate pydantic fields.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        Nested models are also parsed to dictionaries.

        Additionally fields decorated with @property_field are also added.

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

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

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

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

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

        return dict_instance

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

pk_column: sqlalchemy.Column property

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

Returns:

Type Description
sqlalchemy.Column

primary key sqlalchemy column

saved: bool property

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

signals: SignalEmitter property

Exposes signals from model Meta

__eq__(other)

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

Parameters:

Name Type Description Default
other object

other model to compare

required

Returns:

Type Description
bool

result of comparison

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

__getattr__(item)

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

Parameters:

Name Type Description Default
item str

name of attribute

required

Returns:

Type Description
Any

Any

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

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

__init__(*args, **kwargs)

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

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

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

Json fields are automatically loaded/dumped if needed.

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

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

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

Parameters:

Name Type Description Default
args Any

ignored args

()
kwargs Any

keyword arguments - all fields values and some special params

{}

Raises:

Type Description
ModelError

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

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

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

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

    Json fields are automatically loaded/dumped if needed.

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

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

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

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

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

    new_kwargs, through_tmp_dict = self._process_kwargs(kwargs)

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

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

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

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

__same__(other)

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

Parameters:

Name Type Description Default
other NewBaseModel

model to compare to

required

Returns:

Type Description
bool

result of comparison

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

__setattr__(name, value)

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

Parameters:

Name Type Description Default
name str

name of the attribute to set

required
value Any

value of the attribute to set

required

Returns:

Type Description
None

None

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

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

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

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

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

db_backend_name() classmethod

Shortcut to database dialect, cause some dialect require different treatment

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

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

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

Nested models are also parsed to dictionaries.

Additionally fields decorated with @property_field are also added.

Parameters:

Name Type Description Default
exclude_through_models bool

flag to exclude through models from dict

False
exclude_primary_keys bool

flag to exclude primary keys from dict

False
include Union[Set, Dict]

fields to include

None
exclude Union[Set, Dict]

fields to exclude

None
by_alias bool

flag to get values by alias - passed to pydantic

False
skip_defaults bool

flag to not set values - passed to pydantic

None
exclude_unset bool

flag to exclude not set values - passed to pydantic

False
exclude_defaults bool

flag to exclude default values - passed to pydantic

False
exclude_none bool

flag to exclude None values - passed to pydantic

False
exclude_list bool

flag to exclude lists of nested values models from dict

False
relation_map Dict

map of the relations to follow to avoid circural deps

None

Returns:

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

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

    Nested models are also parsed to dictionaries.

    Additionally fields decorated with @property_field are also added.

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

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

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

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

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

    return dict_instance

get_name(lower=True) classmethod

Returns name of the Model class, by default lowercase.

Parameters:

Name Type Description Default
lower bool

flag if name should be set to lowercase

True

Returns:

Type Description
str

name of the model

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

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

get_properties(include, exclude) classmethod

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

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

Parameters:

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

fields to include

required
exclude Union[Set, Dict, None]

fields to exclude

required

Returns:

Type Description
Set[str]

set of property fields names

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

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

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

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

get_relation_model_id(target_field)

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

Parameters:

Name Type Description Default
target_field BaseField

field with relation definition

required

Returns:

Type Description
Optional[int]

value of pk if set

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

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

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

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

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

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

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

pk_type() classmethod

Shortcut to models primary key field type

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

remove(parent, name)

Removes child from relation with given name in RelationshipManager

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

set_save_status(status)

Sets value of the save status

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

update_forward_refs(**localns) classmethod

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

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

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

Sets self_reference flag on models that links to themselves.

Calls the pydantic method to evaluate pydantic fields.

Parameters:

Name Type Description Default
localns Any

local namespace

{}

Returns:

Type Description
None

None

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

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

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

    Sets self_reference flag on models that links to themselves.

    Calls the pydantic method to evaluate pydantic fields.

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

update_from_dict(value_dict)

Updates self with values of fields passed in the dictionary.

Parameters:

Name Type Description Default
value_dict Dict

dictionary of fields names and values

required

Returns:

Type Description
NewBaseModel

self

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

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