Skip to content

newbasemodel

DumpOptions

Bases: TypedDict

model_dump options that apply to the whole tree, so they are forwarded unchanged to every nested related and through model dump.

Source code in ormar/models/newbasemodel.py
Python
105
106
107
108
109
110
111
112
113
114
115
116
117
class DumpOptions(TypedDict):
    """
    ``model_dump`` options that apply to the whole tree, so they are forwarded
    unchanged to every nested related and through model dump.
    """

    mode: str
    by_alias: bool
    exclude_unset: bool
    exclude_defaults: bool
    exclude_none: bool
    exclude_list: bool
    round_trip: bool

NestedDescent dataclass

Per-field locals threaded into the recursive model_dump call when descending into a related field. Returned from _resolve_field_descent only when the field is not handled inline (flattened or skipped).

Source code in ormar/models/newbasemodel.py
Python
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
@dataclass(frozen=True)
class NestedDescent:
    """
    Per-field locals threaded into the recursive ``model_dump`` call when
    descending into a related field. Returned from ``_resolve_field_descent``
    only when the field is not handled inline (flattened or skipped).
    """

    flatten_map: Optional["FlattenMap"]
    relation_map: builtins.dict
    include: Union[set, builtins.dict, None]
    exclude: Union[set, builtins.dict, None]

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."
        )