Skip to content

foreign_key

FkParams

Bases: NamedTuple

Parameters of a relation field derived from the model it leads to.

Attributes:

Name Type Description
annotation Any

pydantic type of the field

column_type Any

SQLAlchemy type of the referencing column

key_only_model type[BaseModel]

pydantic model validating key-only values

Source code in ormar/fields/foreign_key.py
Python
40
41
42
43
44
45
46
47
48
49
50
51
class FkParams(NamedTuple):
    """
    Parameters of a relation field derived from the model it leads to.

    :ivar annotation: pydantic type of the field
    :ivar column_type: SQLAlchemy type of the referencing column
    :ivar key_only_model: pydantic model validating key-only values
    """

    annotation: Any
    column_type: Any
    key_only_model: type[BaseModel]

ForeignKeyField

Bases: BaseField

Actual class returned from ForeignKey function call and stored in model_fields.

Source code in ormar/fields/foreign_key.py
Python
 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
class ForeignKeyField(BaseField):  # type: ignore[misc]
    """
    Actual class returned from ForeignKey function call and stored in model_fields.
    """

    def __init__(self, **kwargs: Any) -> None:
        if TYPE_CHECKING:  # pragma: no cover
            self.__type__: type
            self.to: type["Model"]
        self.ondelete: str = kwargs.pop("ondelete", None)
        self.onupdate: str = kwargs.pop("onupdate", None)
        self.foreign_key_name: Optional[str] = kwargs.pop("foreign_key_name", None)
        self.to_field: Union[str, list[str], tuple[str, ...], None] = kwargs.pop(
            "to_field", None
        )
        self.columns: Optional[dict[str, str]] = kwargs.pop("columns", None)
        self.db_constraint: bool = kwargs.pop("db_constraint", True)
        self.deferred_related_name_checks: list[ForeignKeyField] = []
        super().__init__(**kwargs)

    def construct_constraints(self) -> list:
        """
        Build the SQLAlchemy foreign keys of the field's column from its link,
        one per column pair, named ``foreign_key_name`` or
        ``fk_<owner table>_<target table>_<target column>_<field name>``.
        Built on every call, as SQLAlchemy binds a ForeignKey to one table and
        subclasses need their own.

        :return: SQLAlchemy foreign keys, empty until the target is resolved
        :rtype: list
        """
        if (
            self.virtual
            or not self.db_constraint
            or self.has_unresolved_forward_refs()
            or self.owner.ormar_config.view
        ):
            return []
        owner_table = self.owner.ormar_config.tablename
        target_table = self.to.ormar_config.tablename
        return [
            sqlalchemy.ForeignKey(
                column=qualified_fk_reference(
                    target=self.to, column_alias=pair.target_column
                ),
                ondelete=self.ondelete,
                onupdate=self.onupdate,
                name=self.foreign_key_name
                or f"fk_{owner_table}_{target_table}_{pair.target_column}_{self.name}",
            )
            for pair in self.link.pairs
        ]

    @property
    def kind(self) -> RelationKind:
        """
        :return: forward or reverse side of a foreign key or one-to-one relation
        :rtype: RelationKind
        """
        return FOREIGN_KEY_KINDS[(self.one_to_one, self.virtual)]

    def get_related_name(self) -> str:
        """
        Returns name to use for reverse relation.
        It's either set as `related_name` or by default it's owner model. get_name + 's'
        :return: name of the related_name or default related name.
        :rtype: str
        """
        suffix = "" if self.one_to_one else "s"
        return self.related_name or self.owner.get_name() + suffix

    def default_target_field_name(self) -> str:
        """
        Returns default target model name on through model.
        :return: name of the field
        :rtype: str
        """
        prefix = "from_" if self.self_reference else ""
        return self.through_reverse_relation_name or f"{prefix}{self.to.get_name()}"

    def default_source_field_name(self) -> str:
        """
        Returns default target model name on through model.
        :return: name of the field
        :rtype: str
        """
        prefix = "to_" if self.self_reference else ""
        return self.through_relation_name or f"{prefix}{self.owner.get_name()}"

    def get_filter_clause_target(self) -> type["Model"]:
        return self.to

    @property
    def link(self) -> RelationLink:
        """
        Columns connecting the owner's table to the table of the related model,
        built once per owner and target: a field copied to another model
        (inheritance) or re-targeted (forward refs) builds its own link.

        :return: link from the owner to the related model
        :rtype: RelationLink
        """
        cache_key = (self.owner, self.to, self.through)
        cached = self.__dict__.get("link_cache")
        if cached is not None and cached[0] == cache_key:
            return cached[1]
        link = self.build_link()
        self.__dict__["link_cache"] = (cache_key, link)
        return link

    def build_link(self) -> RelationLink:
        """
        A foreign key links its own column to the target's primary key, a
        reverse relation is the mirror of the foreign key it was created from.

        :return: link from the owner to the related model
        :rtype: RelationLink
        """
        if self.virtual:
            forward = self.to.ormar_config.model_fields[self.get_related_name()]
            return cast("ForeignKeyField", forward).link.mirrored()
        columns = referenced_columns(to=self.to, to_field=self.to_field)
        return RelationLink(
            source=self.owner,
            target=self.to,
            pairs=tuple(
                ColumnPair(
                    source_field=self.name,
                    source_column=self.local_column(
                        target_column=column, several=len(columns) > 1
                    ),
                    target_field=field,
                    target_column=column,
                )
                for column, field in columns.items()
            ),
        )

    def target_fields(self) -> tuple[str, ...]:
        """
        :return: fields of the related model the foreign key references: its
            ``to_field`` or its primary key fields
        :rtype: tuple[str, ...]
        """
        names = to_field_names(to_field=self.to_field)
        if names is not None:
            return names
        return self.to.ormar_config.pk.fields

    def local_column(self, target_column: str, several: bool) -> str:
        """
        :param target_column: referenced column of the related model's table
        :type target_column: str
        :param several: whether the foreign key references several columns
        :type several: bool
        :return: name of the owner's column storing it: from ``columns=``, the
            field's own column for a single-column key, or
            ``<field>_<referenced column>`` for keys of several columns
        :rtype: str
        """
        if self.columns is not None:
            return self.columns[target_column]
        if not several:
            return self.get_alias()
        return f"{self.name}_{target_column}"

    def get_columns(self) -> list[sqlalchemy.Column]:
        """
        :return: the owner's columns of the foreign key, one per referenced
            column (a placeholder single column until a forward reference is
            resolved)
        :rtype: list[sqlalchemy.Column]
        """
        if self.has_unresolved_forward_refs():
            return [self.get_column(self.get_alias())]
        pairs = self.link.pairs
        if len(pairs) == 1:
            return [self.get_column(pairs[0].source_column)]
        return [
            sqlalchemy.Column(
                name=pair.source_column,
                type_=column_type(
                    model=self.to, field=pair.target_field, column=pair.target_column
                ),
                nullable=self.sql_nullable,
                primary_key=self.primary_key,
                autoincrement=False,
            )
            for pair in pairs
        ]

    def column_aliases(self) -> tuple[str, ...]:
        """
        :return: the owner's column names of the foreign key
        :rtype: tuple[str, ...]
        """
        if self.virtual or self.has_unresolved_forward_refs():
            return (self.get_alias(),)
        return self.link.source_columns()

    def construct_table_constraints(self) -> list:
        """
        :return: the table-level items of a foreign key of several columns:
            its ``FOREIGN KEY (a, b) REFERENCES t (x, y)``, and a composite
            unique constraint / index when the field is unique / indexed;
            empty for other fields
        :rtype: list
        """
        if (
            not self.kind.holds_columns
            or self.has_unresolved_forward_refs()
            or self.owner.ormar_config.view
        ):
            return []
        pairs = self.link.pairs
        if len(pairs) == 1:
            return []
        columns = [pair.source_column for pair in pairs]
        owner_table = self.owner.ormar_config.tablename
        target_table = self.to.ormar_config.tablename
        items: list = []
        if self.db_constraint:
            items.append(
                sqlalchemy.ForeignKeyConstraint(
                    columns=columns,
                    refcolumns=[
                        qualified_fk_reference(
                            target=self.to, column_alias=pair.target_column
                        )
                        for pair in pairs
                    ],
                    ondelete=self.ondelete,
                    onupdate=self.onupdate,
                    name=self.foreign_key_name
                    or f"fk_{owner_table}_{target_table}_{self.name}",
                )
            )
        if self.unique:
            items.append(
                sqlalchemy.UniqueConstraint(
                    *columns, name=f"uc_{owner_table}_{self.name}"
                )
            )
        if self.index:
            items.append(sqlalchemy.Index(f"ix_{owner_table}_{self.name}", *columns))
        return items

    def _evaluate_forward_ref(
        self, globalns: Any, localns: Any, is_through: bool = False
    ) -> None:
        target = "through" if is_through else "to"
        target_obj = getattr(self, target)
        if sys.version_info.minor <= 8:  # pragma: no cover
            evaluated = target_obj._evaluate(globalns, localns)
        else:  # pragma: no cover
            evaluated = target_obj._evaluate(globalns, localns, recursive_guard=set())
        setattr(self, target, evaluated)

    def evaluate_forward_ref(self, globalns: Any, localns: Any) -> None:
        """
        Evaluates the ForwardRef to actual Field based on global and local namespaces

        :param globalns: global namespace
        :type globalns: Any
        :param localns: local namespace
        :type localns: Any
        :return: None
        :rtype: None
        """
        if self.to.__class__ == ForwardRef:
            self._evaluate_forward_ref(globalns, localns)
            validate_view_target(
                to=self.to, virtual=self.virtual, db_constraint=self.db_constraint
            )
            params = populate_fk_params_based_on_to_model(
                to=self.to,
                nullable=self.nullable,
                virtual=self.virtual,
                to_field=self.to_field,
            )
            if not self.virtual:
                validate_link_columns(
                    to=self.to,
                    to_field=self.to_field,
                    columns=self.columns,
                    name=self.db_alias,
                )
            self.__type__ = params.annotation
            self.column_type = params.column_type
            self.to_key_only = params.key_only_model

    def _extract_model_from_sequence(
        self, value: list, child: "Model", to_register: bool
    ) -> list["Model"]:
        """
        Takes a list of Models and registers them on parent.
        Registration is mutual, so children have also reference to parent.

        Used in reverse FK relations.

        :param value: list of Model
        :type value: list
        :param child: child/ related Model
        :type child: Model
        :param to_register: flag if the relation should be set in RelationshipManager
        :type to_register: bool
        :return: list (if needed) registered Models
        :rtype: list["Model"]
        """
        return [
            self.expand_relationship(  # type: ignore
                # a key of several columns given as a JSON list
                value=tuple(val) if val.__class__ is list else val,
                child=child,
                to_register=to_register,
            )
            for val in value
        ]

    def _construct_model_from_dict(
        self, value: dict, child: "Model", to_register: bool
    ) -> "Model":
        """
        Takes a dictionary, creates a instance and registers it for parent.
        If dictionary holds only the referenced key fields it is a __pk_only__
        model. Related fields may be present if they are None, empty or the
        relation back to the child (as in serialized responses), any other
        related value makes it a full model, so nested related models are kept.
        Registration is mutual, so children have also reference to parent.

        Used in normal FK for dictionaries.

        :param value: dictionary of a Model
        :type value: dict
        :param child: child/ related Model
        :type child: Model
        :param to_register: flag if the relation should be set in RelationshipManager
        :type to_register: bool
        :return: (if needed) registered Model
        :rtype: Model
        """
        key_only_model = None
        target_fields = self.target_fields()
        related_names = self.to.extract_related_names()
        own_keys = set(value.keys()) - related_names
        nested_keys = value.keys() & related_names - {self.get_related_name()}
        if (
            own_keys == set(target_fields)
            and all(value.get(field) is not None for field in target_fields)
            and all(value[name] is None or value[name] == [] for name in nested_keys)
            and not self.is_through
        ):
            key_only_model = self.to_key_only(**value)
            model = cast(
                "Model",
                self.to._internal_construct(_pk_only=True, _excluded=None, **value),
            )
        else:
            model = self.to(**value)
        if to_register:
            self.register_relation(model=model, child=child)
        return key_only_model if key_only_model is not None else model

    def _construct_model_from_pk(
        self, value: Any, child: "Model", to_register: bool
    ) -> "Model":
        """
        Takes a pk value, creates a dummy instance and registers it for parent.
        Registration is mutual, so children have also reference to parent.

        Used in normal FK for dictionaries.

        :param value: value of a related pk / fk column
        :type value: Any
        :param child: child/ related Model
        :type child: Model
        :param to_register: flag if the relation should be set in RelationshipManager
        :type to_register: bool
        :return: (if needed) registered Model
        :rtype: Model
        """
        model = self.construct_key_only_model(value=value)
        if to_register:
            self.register_relation(model=model, child=child)
        return model

    def construct_key_only_model(self, value: Any) -> "Model":
        """
        Takes a key value and creates an instance of the related model with
        only the key populated, without registering it on any side.

        :param value: value of a related pk / fk column
        :type value: Any
        :raises RelationshipInstanceError: if value does not match the pk type
        :return: related model with only pk set
        :rtype: Model
        """
        if isinstance(value, self.to_key_only):
            values = {field: getattr(value, field) for field in self.target_fields()}
            return key_only_instance(target=self.to, values=values)
        value_type = self.target_value_type()
        if value_type == uuid.UUID and isinstance(value, str):  # pragma: nocover
            value = uuid.UUID(value)
        if not isinstance(value, value_type):
            raise RelationshipInstanceError(
                f"Relationship error - ForeignKey {self.to.__name__} "
                f"is of type {value_type} "
                f"while {type(value)} passed as a parameter."
            )
        return key_only_instance(target=self.to, values=self.target_values(value=value))

    def target_value_of(self, related: Any) -> Any:
        """
        :param related: related model, its key-only model, a dict of its
            fields or a raw value
        :type related: Any
        :return: the value this foreign key stores for it, ``None`` when the
            related model lacks it
        :rtype: Any
        """
        return self.link.values_for(related=related)[self.name]

    def flat_fields(self) -> tuple[str, ...]:
        """
        :return: fields of a related model that represent it in flattened
            output: the referenced fields of a foreign key, the primary key
            of a reverse or many-to-many relation
        :rtype: tuple[str, ...]
        """
        if not self.kind.holds_columns:
            return self.to.ormar_config.pk.fields
        return self.target_fields()

    def flat_value(self, related: "Model") -> Any:
        """
        Represent a related model in flattened output (``flatten_fields``)::

            Track.album -> 4
            Address.country (to_field="iso_code") -> "PL"
            OrderLine.order (two columns) -> {"tenant_id": 1, "number": 7}
            Shift.membership -> {"tenant_id": 1, "member": {...}, "team": {...}}

        A referenced field that is itself a relation (a key holding a foreign
        key) is represented by its own flattened value.

        :param related: related model
        :type related: Model
        :return: the referenced value, a dict of them for several fields
        :rtype: Any
        """
        return self.flat_from_columns(
            values={
                column: column_value(model=self.to, data=related, column=column)
                for column in self.flat_columns()
            }
        )

    def flat_columns(self) -> tuple[str, ...]:
        """
        :return: columns of the related model holding ``flat_fields``
        :rtype: tuple[str, ...]
        """
        if not self.kind.holds_columns:
            return self.to.ormar_config.pk.column_aliases()
        return self.link.target_columns()

    def flat_from_columns(self, values: dict[str, Any]) -> Any:
        """
        Build the flattened representation of a related model (see
        ``flat_value``) out of the values of its ``flat_columns``.

        :param values: values of the related model's columns by column name
        :type values: dict[str, Any]
        :return: the referenced value, a dict of them for several fields
        :rtype: Any
        """
        fields = self.flat_fields()
        flat = {
            field: flat_field_from_columns(model=self.to, field=field, values=values)
            for field in fields
        }
        return flat[fields[0]] if len(fields) == 1 else flat

    def flat_value_type(self) -> Any:
        """
        :return: python type of a flattened related model (see ``flat_value``)
        :rtype: Any
        """
        fields = self.flat_fields()
        if len(fields) > 1:
            return key_dict_type(target=self.to, fields=fields)
        return flat_field_type(model=self.to, field=fields[0])

    def target_value_type(self) -> Any:
        """
        :return: python type of a raw value of the relation: the ``to_field``
            type or the related model's key type
        :rtype: Any
        """
        names = to_field_names(to_field=self.to_field)
        if names is None:
            return self.to.ormar_config.pk.python_type()
        if len(names) == 1:
            return self.to.ormar_config.model_fields[names[0]].__type__
        return tuple

    def target_values(self, value: Any) -> dict[str, Any]:
        """
        :param value: raw value of the relation
        :type value: Any
        :return: the value split into the referenced fields of the related model
        :rtype: dict[str, Any]
        """
        names = to_field_names(to_field=self.to_field)
        if names is None:
            return self.to.ormar_config.pk.to_dict(value=value)
        return dict(zip(names, key_parts(value=value, size=len(names))))

    def register_relation(self, model: "Model", child: "Model") -> None:
        """
        Registers relation between parent and child in relation manager.
        Relation manager is kep on each model (different instance).

        Used in Metaclass and sometimes some relations are missing
        (i.e. cloned Models in fastapi might miss one).

        :param model: parent model (with relation definition)
        :type model: Model class
        :param child: child model
        :type child: Model class
        """
        model._orm.add(parent=model, child=child, field=self)

    def has_unresolved_forward_refs(self) -> bool:
        """
        Verifies if the filed has any ForwardRefs that require updating before the
        model can be used.

        :return: result of the check
        :rtype: bool
        """
        return self.to.__class__ == ForwardRef

    @cached_property
    def _constructor_dispatch(self) -> dict[str, Any]:
        """
        Per-field map from input class name to the constructor handling that
        shape. Built once at first access — by the time
        ``expand_relationship`` runs, ``_verify_model_can_be_initialized``
        has already gated on ``requires_ref_update``, so the bound methods
        captured here are stable.

        :return: dispatch table for the slow path of ``expand_relationship``
        :rtype: dict[str, Any]
        """
        return {
            "dict": self._construct_model_from_dict,
            "list": self._extract_model_from_sequence,
        }

    def expand_relationship(
        self,
        value: Any,
        child: Union["Model", "NewBaseModel"],
        to_register: bool = True,
    ) -> Optional[Union["Model", list["Model"]]]:
        """
        For relations the child model is first constructed (if needed),
        registered in relation and returned.
        For relation fields the value can be a pk value (Any type of field),
        dict (from Model) or actual instance/list of a "Model".

        Selects the appropriate constructor based on a passed value.

        :param value: a Model field value, returned untouched for non relation fields.
        :type value: Any
        :param child: a child Model to register
        :type child: Union["Model", "NewBaseModel"]
        :param to_register: flag if the relation should be set in RelationshipManager
        :type to_register: bool
        :return: returns a Model or a list of Models
        :rtype: Optional[Union["Model", list["Model"]]]
        """
        if value is None:
            return [] if self.kind.many else None
        # Fast path: ``value`` is already a Model of ``self.to``. Dominant
        # case in row materialization and in user kwargs that pass
        # constructed Models directly. Skips the dispatch table and the
        # ``_register_existing_model`` indirection entirely.
        if value.__class__ is self.to:
            if to_register:
                self.register_relation(model=value, child=cast("Model", child))
            return value
        if value.__class__ is list and self.kind.holds_columns:
            # a key of several columns given as a JSON list
            value = tuple(value)
        return self._constructor_dispatch.get(
            value.__class__.__name__, self._construct_model_from_pk
        )(value, child, to_register)

    def get_relation_name(self) -> str:  # pragma: no cover
        """
        Returns name of the relation, which can be a own name or through model
        names for m2m models

        :return: result of the check
        :rtype: bool
        """
        return self.name

kind property

Returns:

Type Description
RelationKind

forward or reverse side of a foreign key or one-to-one relation

Columns connecting the owner's table to the table of the related model, built once per owner and target: a field copied to another model (inheritance) or re-targeted (forward refs) builds its own link.

Returns:

Type Description
RelationLink

link from the owner to the related model

A foreign key links its own column to the target's primary key, a reverse relation is the mirror of the foreign key it was created from.

Returns:

Type Description
RelationLink

link from the owner to the related model

Source code in ormar/fields/foreign_key.py
Python
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
def build_link(self) -> RelationLink:
    """
    A foreign key links its own column to the target's primary key, a
    reverse relation is the mirror of the foreign key it was created from.

    :return: link from the owner to the related model
    :rtype: RelationLink
    """
    if self.virtual:
        forward = self.to.ormar_config.model_fields[self.get_related_name()]
        return cast("ForeignKeyField", forward).link.mirrored()
    columns = referenced_columns(to=self.to, to_field=self.to_field)
    return RelationLink(
        source=self.owner,
        target=self.to,
        pairs=tuple(
            ColumnPair(
                source_field=self.name,
                source_column=self.local_column(
                    target_column=column, several=len(columns) > 1
                ),
                target_field=field,
                target_column=column,
            )
            for column, field in columns.items()
        ),
    )

column_aliases()

Returns:

Type Description
tuple[str, ...]

the owner's column names of the foreign key

Source code in ormar/fields/foreign_key.py
Python
745
746
747
748
749
750
751
752
def column_aliases(self) -> tuple[str, ...]:
    """
    :return: the owner's column names of the foreign key
    :rtype: tuple[str, ...]
    """
    if self.virtual or self.has_unresolved_forward_refs():
        return (self.get_alias(),)
    return self.link.source_columns()

construct_constraints()

Build the SQLAlchemy foreign keys of the field's column from its link, one per column pair, named foreign_key_name or fk_<owner table>_<target table>_<target column>_<field name>. Built on every call, as SQLAlchemy binds a ForeignKey to one table and subclasses need their own.

Returns:

Type Description
list

SQLAlchemy foreign keys, empty until the target is resolved

Source code in ormar/fields/foreign_key.py
Python
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
def construct_constraints(self) -> list:
    """
    Build the SQLAlchemy foreign keys of the field's column from its link,
    one per column pair, named ``foreign_key_name`` or
    ``fk_<owner table>_<target table>_<target column>_<field name>``.
    Built on every call, as SQLAlchemy binds a ForeignKey to one table and
    subclasses need their own.

    :return: SQLAlchemy foreign keys, empty until the target is resolved
    :rtype: list
    """
    if (
        self.virtual
        or not self.db_constraint
        or self.has_unresolved_forward_refs()
        or self.owner.ormar_config.view
    ):
        return []
    owner_table = self.owner.ormar_config.tablename
    target_table = self.to.ormar_config.tablename
    return [
        sqlalchemy.ForeignKey(
            column=qualified_fk_reference(
                target=self.to, column_alias=pair.target_column
            ),
            ondelete=self.ondelete,
            onupdate=self.onupdate,
            name=self.foreign_key_name
            or f"fk_{owner_table}_{target_table}_{pair.target_column}_{self.name}",
        )
        for pair in self.link.pairs
    ]

construct_key_only_model(value)

Takes a key value and creates an instance of the related model with only the key populated, without registering it on any side.

Parameters:

Name Type Description Default
value Any

value of a related pk / fk column

required

Returns:

Type Description
Model

related model with only pk set

Raises:

Type Description
RelationshipInstanceError

if value does not match the pk type

Source code in ormar/fields/foreign_key.py
Python
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
def construct_key_only_model(self, value: Any) -> "Model":
    """
    Takes a key value and creates an instance of the related model with
    only the key populated, without registering it on any side.

    :param value: value of a related pk / fk column
    :type value: Any
    :raises RelationshipInstanceError: if value does not match the pk type
    :return: related model with only pk set
    :rtype: Model
    """
    if isinstance(value, self.to_key_only):
        values = {field: getattr(value, field) for field in self.target_fields()}
        return key_only_instance(target=self.to, values=values)
    value_type = self.target_value_type()
    if value_type == uuid.UUID and isinstance(value, str):  # pragma: nocover
        value = uuid.UUID(value)
    if not isinstance(value, value_type):
        raise RelationshipInstanceError(
            f"Relationship error - ForeignKey {self.to.__name__} "
            f"is of type {value_type} "
            f"while {type(value)} passed as a parameter."
        )
    return key_only_instance(target=self.to, values=self.target_values(value=value))

construct_table_constraints()

Returns:

Type Description
list

the table-level items of a foreign key of several columns: its FOREIGN KEY (a, b) REFERENCES t (x, y), and a composite unique constraint / index when the field is unique / indexed; empty for other fields

Source code in ormar/fields/foreign_key.py
Python
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
def construct_table_constraints(self) -> list:
    """
    :return: the table-level items of a foreign key of several columns:
        its ``FOREIGN KEY (a, b) REFERENCES t (x, y)``, and a composite
        unique constraint / index when the field is unique / indexed;
        empty for other fields
    :rtype: list
    """
    if (
        not self.kind.holds_columns
        or self.has_unresolved_forward_refs()
        or self.owner.ormar_config.view
    ):
        return []
    pairs = self.link.pairs
    if len(pairs) == 1:
        return []
    columns = [pair.source_column for pair in pairs]
    owner_table = self.owner.ormar_config.tablename
    target_table = self.to.ormar_config.tablename
    items: list = []
    if self.db_constraint:
        items.append(
            sqlalchemy.ForeignKeyConstraint(
                columns=columns,
                refcolumns=[
                    qualified_fk_reference(
                        target=self.to, column_alias=pair.target_column
                    )
                    for pair in pairs
                ],
                ondelete=self.ondelete,
                onupdate=self.onupdate,
                name=self.foreign_key_name
                or f"fk_{owner_table}_{target_table}_{self.name}",
            )
        )
    if self.unique:
        items.append(
            sqlalchemy.UniqueConstraint(
                *columns, name=f"uc_{owner_table}_{self.name}"
            )
        )
    if self.index:
        items.append(sqlalchemy.Index(f"ix_{owner_table}_{self.name}", *columns))
    return items

default_source_field_name()

Returns default target model name on through model.

Returns:

Type Description
str

name of the field

Source code in ormar/fields/foreign_key.py
Python
634
635
636
637
638
639
640
641
def default_source_field_name(self) -> str:
    """
    Returns default target model name on through model.
    :return: name of the field
    :rtype: str
    """
    prefix = "to_" if self.self_reference else ""
    return self.through_relation_name or f"{prefix}{self.owner.get_name()}"

default_target_field_name()

Returns default target model name on through model.

Returns:

Type Description
str

name of the field

Source code in ormar/fields/foreign_key.py
Python
625
626
627
628
629
630
631
632
def default_target_field_name(self) -> str:
    """
    Returns default target model name on through model.
    :return: name of the field
    :rtype: str
    """
    prefix = "from_" if self.self_reference else ""
    return self.through_reverse_relation_name or f"{prefix}{self.to.get_name()}"

evaluate_forward_ref(globalns, localns)

Evaluates the ForwardRef to actual Field based on global and local namespaces

Parameters:

Name Type Description Default
globalns Any

global namespace

required
localns Any

local namespace

required

Returns:

Type Description
None

None

Source code in ormar/fields/foreign_key.py
Python
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
def evaluate_forward_ref(self, globalns: Any, localns: Any) -> None:
    """
    Evaluates the ForwardRef to actual Field based on global and local namespaces

    :param globalns: global namespace
    :type globalns: Any
    :param localns: local namespace
    :type localns: Any
    :return: None
    :rtype: None
    """
    if self.to.__class__ == ForwardRef:
        self._evaluate_forward_ref(globalns, localns)
        validate_view_target(
            to=self.to, virtual=self.virtual, db_constraint=self.db_constraint
        )
        params = populate_fk_params_based_on_to_model(
            to=self.to,
            nullable=self.nullable,
            virtual=self.virtual,
            to_field=self.to_field,
        )
        if not self.virtual:
            validate_link_columns(
                to=self.to,
                to_field=self.to_field,
                columns=self.columns,
                name=self.db_alias,
            )
        self.__type__ = params.annotation
        self.column_type = params.column_type
        self.to_key_only = params.key_only_model

expand_relationship(value, child, to_register=True)

For relations the child model is first constructed (if needed), registered in relation and returned. For relation fields the value can be a pk value (Any type of field), dict (from Model) or actual instance/list of a "Model".

Selects the appropriate constructor based on a passed value.

Parameters:

Name Type Description Default
value Any

a Model field value, returned untouched for non relation fields.

required
child Union[Model, NewBaseModel]

a child Model to register

required
to_register bool

flag if the relation should be set in RelationshipManager

True

Returns:

Type Description
Optional[Union["Model", list["Model"]]]

returns a Model or a list of Models

Source code in ormar/fields/foreign_key.py
Python
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
def expand_relationship(
    self,
    value: Any,
    child: Union["Model", "NewBaseModel"],
    to_register: bool = True,
) -> Optional[Union["Model", list["Model"]]]:
    """
    For relations the child model is first constructed (if needed),
    registered in relation and returned.
    For relation fields the value can be a pk value (Any type of field),
    dict (from Model) or actual instance/list of a "Model".

    Selects the appropriate constructor based on a passed value.

    :param value: a Model field value, returned untouched for non relation fields.
    :type value: Any
    :param child: a child Model to register
    :type child: Union["Model", "NewBaseModel"]
    :param to_register: flag if the relation should be set in RelationshipManager
    :type to_register: bool
    :return: returns a Model or a list of Models
    :rtype: Optional[Union["Model", list["Model"]]]
    """
    if value is None:
        return [] if self.kind.many else None
    # Fast path: ``value`` is already a Model of ``self.to``. Dominant
    # case in row materialization and in user kwargs that pass
    # constructed Models directly. Skips the dispatch table and the
    # ``_register_existing_model`` indirection entirely.
    if value.__class__ is self.to:
        if to_register:
            self.register_relation(model=value, child=cast("Model", child))
        return value
    if value.__class__ is list and self.kind.holds_columns:
        # a key of several columns given as a JSON list
        value = tuple(value)
    return self._constructor_dispatch.get(
        value.__class__.__name__, self._construct_model_from_pk
    )(value, child, to_register)

flat_columns()

Returns:

Type Description
tuple[str, ...]

columns of the related model holding flat_fields

Source code in ormar/fields/foreign_key.py
Python
1011
1012
1013
1014
1015
1016
1017
1018
def flat_columns(self) -> tuple[str, ...]:
    """
    :return: columns of the related model holding ``flat_fields``
    :rtype: tuple[str, ...]
    """
    if not self.kind.holds_columns:
        return self.to.ormar_config.pk.column_aliases()
    return self.link.target_columns()

flat_fields()

Returns:

Type Description
tuple[str, ...]

fields of a related model that represent it in flattened output: the referenced fields of a foreign key, the primary key of a reverse or many-to-many relation

Source code in ormar/fields/foreign_key.py
Python
976
977
978
979
980
981
982
983
984
985
def flat_fields(self) -> tuple[str, ...]:
    """
    :return: fields of a related model that represent it in flattened
        output: the referenced fields of a foreign key, the primary key
        of a reverse or many-to-many relation
    :rtype: tuple[str, ...]
    """
    if not self.kind.holds_columns:
        return self.to.ormar_config.pk.fields
    return self.target_fields()

flat_from_columns(values)

Build the flattened representation of a related model (see flat_value) out of the values of its flat_columns.

Parameters:

Name Type Description Default
values dict[str, Any]

values of the related model's columns by column name

required

Returns:

Type Description
Any

the referenced value, a dict of them for several fields

Source code in ormar/fields/foreign_key.py
Python
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
def flat_from_columns(self, values: dict[str, Any]) -> Any:
    """
    Build the flattened representation of a related model (see
    ``flat_value``) out of the values of its ``flat_columns``.

    :param values: values of the related model's columns by column name
    :type values: dict[str, Any]
    :return: the referenced value, a dict of them for several fields
    :rtype: Any
    """
    fields = self.flat_fields()
    flat = {
        field: flat_field_from_columns(model=self.to, field=field, values=values)
        for field in fields
    }
    return flat[fields[0]] if len(fields) == 1 else flat

flat_value(related)

Represent a related model in flattened output (flatten_fields)::

Text Only
1
2
3
4
Track.album -> 4
Address.country (to_field="iso_code") -> "PL"
OrderLine.order (two columns) -> {"tenant_id": 1, "number": 7}
Shift.membership -> {"tenant_id": 1, "member": {...}, "team": {...}}

A referenced field that is itself a relation (a key holding a foreign key) is represented by its own flattened value.

Parameters:

Name Type Description Default
related Model

related model

required

Returns:

Type Description
Any

the referenced value, a dict of them for several fields

Source code in ormar/fields/foreign_key.py
Python
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
def flat_value(self, related: "Model") -> Any:
    """
    Represent a related model in flattened output (``flatten_fields``)::

        Track.album -> 4
        Address.country (to_field="iso_code") -> "PL"
        OrderLine.order (two columns) -> {"tenant_id": 1, "number": 7}
        Shift.membership -> {"tenant_id": 1, "member": {...}, "team": {...}}

    A referenced field that is itself a relation (a key holding a foreign
    key) is represented by its own flattened value.

    :param related: related model
    :type related: Model
    :return: the referenced value, a dict of them for several fields
    :rtype: Any
    """
    return self.flat_from_columns(
        values={
            column: column_value(model=self.to, data=related, column=column)
            for column in self.flat_columns()
        }
    )

flat_value_type()

Returns:

Type Description
Any

python type of a flattened related model (see flat_value)

Source code in ormar/fields/foreign_key.py
Python
1037
1038
1039
1040
1041
1042
1043
1044
1045
def flat_value_type(self) -> Any:
    """
    :return: python type of a flattened related model (see ``flat_value``)
    :rtype: Any
    """
    fields = self.flat_fields()
    if len(fields) > 1:
        return key_dict_type(target=self.to, fields=fields)
    return flat_field_type(model=self.to, field=fields[0])

get_columns()

Returns:

Type Description
list[sqlalchemy.Column]

the owner's columns of the foreign key, one per referenced column (a placeholder single column until a forward reference is resolved)

Source code in ormar/fields/foreign_key.py
Python
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
def get_columns(self) -> list[sqlalchemy.Column]:
    """
    :return: the owner's columns of the foreign key, one per referenced
        column (a placeholder single column until a forward reference is
        resolved)
    :rtype: list[sqlalchemy.Column]
    """
    if self.has_unresolved_forward_refs():
        return [self.get_column(self.get_alias())]
    pairs = self.link.pairs
    if len(pairs) == 1:
        return [self.get_column(pairs[0].source_column)]
    return [
        sqlalchemy.Column(
            name=pair.source_column,
            type_=column_type(
                model=self.to, field=pair.target_field, column=pair.target_column
            ),
            nullable=self.sql_nullable,
            primary_key=self.primary_key,
            autoincrement=False,
        )
        for pair in pairs
    ]

Returns name to use for reverse relation. It's either set as related_name or by default it's owner model. get_name + 's'

Returns:

Type Description
str

name of the related_name or default related name.

Source code in ormar/fields/foreign_key.py
Python
615
616
617
618
619
620
621
622
623
def get_related_name(self) -> str:
    """
    Returns name to use for reverse relation.
    It's either set as `related_name` or by default it's owner model. get_name + 's'
    :return: name of the related_name or default related name.
    :rtype: str
    """
    suffix = "" if self.one_to_one else "s"
    return self.related_name or self.owner.get_name() + suffix

get_relation_name()

Returns name of the relation, which can be a own name or through model names for m2m models

Returns:

Type Description
bool

result of the check

Source code in ormar/fields/foreign_key.py
Python
1154
1155
1156
1157
1158
1159
1160
1161
1162
def get_relation_name(self) -> str:  # pragma: no cover
    """
    Returns name of the relation, which can be a own name or through model
    names for m2m models

    :return: result of the check
    :rtype: bool
    """
    return self.name

has_unresolved_forward_refs()

Verifies if the filed has any ForwardRefs that require updating before the model can be used.

Returns:

Type Description
bool

result of the check

Source code in ormar/fields/foreign_key.py
Python
1087
1088
1089
1090
1091
1092
1093
1094
1095
def has_unresolved_forward_refs(self) -> bool:
    """
    Verifies if the filed has any ForwardRefs that require updating before the
    model can be used.

    :return: result of the check
    :rtype: bool
    """
    return self.to.__class__ == ForwardRef

local_column(target_column, several)

Parameters:

Name Type Description Default
target_column str

referenced column of the related model's table

required
several bool

whether the foreign key references several columns

required

Returns:

Type Description
str

name of the owner's column storing it: from columns=, the field's own column for a single-column key, or <field>_<referenced column> for keys of several columns

Source code in ormar/fields/foreign_key.py
Python
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
def local_column(self, target_column: str, several: bool) -> str:
    """
    :param target_column: referenced column of the related model's table
    :type target_column: str
    :param several: whether the foreign key references several columns
    :type several: bool
    :return: name of the owner's column storing it: from ``columns=``, the
        field's own column for a single-column key, or
        ``<field>_<referenced column>`` for keys of several columns
    :rtype: str
    """
    if self.columns is not None:
        return self.columns[target_column]
    if not several:
        return self.get_alias()
    return f"{self.name}_{target_column}"

register_relation(model, child)

Registers relation between parent and child in relation manager. Relation manager is kep on each model (different instance).

Used in Metaclass and sometimes some relations are missing (i.e. cloned Models in fastapi might miss one).

Parameters:

Name Type Description Default
model Model

parent model (with relation definition)

required
child Model

child model

required
Source code in ormar/fields/foreign_key.py
Python
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
def register_relation(self, model: "Model", child: "Model") -> None:
    """
    Registers relation between parent and child in relation manager.
    Relation manager is kep on each model (different instance).

    Used in Metaclass and sometimes some relations are missing
    (i.e. cloned Models in fastapi might miss one).

    :param model: parent model (with relation definition)
    :type model: Model class
    :param child: child model
    :type child: Model class
    """
    model._orm.add(parent=model, child=child, field=self)

target_fields()

Returns:

Type Description
tuple[str, ...]

fields of the related model the foreign key references: its to_field or its primary key fields

Source code in ormar/fields/foreign_key.py
Python
692
693
694
695
696
697
698
699
700
701
def target_fields(self) -> tuple[str, ...]:
    """
    :return: fields of the related model the foreign key references: its
        ``to_field`` or its primary key fields
    :rtype: tuple[str, ...]
    """
    names = to_field_names(to_field=self.to_field)
    if names is not None:
        return names
    return self.to.ormar_config.pk.fields

target_value_of(related)

Parameters:

Name Type Description Default
related Any

related model, its key-only model, a dict of its fields or a raw value

required

Returns:

Type Description
Any

the value this foreign key stores for it, None when the related model lacks it

Source code in ormar/fields/foreign_key.py
Python
965
966
967
968
969
970
971
972
973
974
def target_value_of(self, related: Any) -> Any:
    """
    :param related: related model, its key-only model, a dict of its
        fields or a raw value
    :type related: Any
    :return: the value this foreign key stores for it, ``None`` when the
        related model lacks it
    :rtype: Any
    """
    return self.link.values_for(related=related)[self.name]

target_value_type()

Returns:

Type Description
Any

python type of a raw value of the relation: the to_field type or the related model's key type

Source code in ormar/fields/foreign_key.py
Python
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
def target_value_type(self) -> Any:
    """
    :return: python type of a raw value of the relation: the ``to_field``
        type or the related model's key type
    :rtype: Any
    """
    names = to_field_names(to_field=self.to_field)
    if names is None:
        return self.to.ormar_config.pk.python_type()
    if len(names) == 1:
        return self.to.ormar_config.model_fields[names[0]].__type__
    return tuple

target_values(value)

Parameters:

Name Type Description Default
value Any

raw value of the relation

required

Returns:

Type Description
dict[str, Any]

the value split into the referenced fields of the related model

Source code in ormar/fields/foreign_key.py
Python
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
def target_values(self, value: Any) -> dict[str, Any]:
    """
    :param value: raw value of the relation
    :type value: Any
    :return: the value split into the referenced fields of the related model
    :rtype: dict[str, Any]
    """
    names = to_field_names(to_field=self.to_field)
    if names is None:
        return self.to.ormar_config.pk.to_dict(value=value)
    return dict(zip(names, key_parts(value=value, size=len(names))))

ForeignKey(to, *, name=None, unique=False, nullable=None, related_name=None, virtual=False, onupdate=None, ondelete=None, foreign_key_name=None, **kwargs)

Python
ForeignKey(to: type[T], **kwargs: Any) -> T
Python
ForeignKey(to: ForwardRef, **kwargs: Any) -> Model

Despite a name it's a function that returns constructed ForeignKeyField. This function is actually used in model declaration (as ormar.ForeignKey(ToModel)).

Accepts number of relation setting parameters as well as all BaseField ones.

Parameters:

Name Type Description Default
to Union[type[T], ForwardRef]

target related ormar Model

required
name Optional[str]

name of the database field - later called alias

None
unique bool

parameter passed to sqlalchemy.ForeignKey, unique flag

False
nullable Optional[bool]

marks field as optional/ required; defaults to optional, and to required for a foreign key in the primary key

None
related_name Optional[str]

name of reversed FK relation populated for you on to model

None
virtual bool

marks if relation is virtual. It is for reversed FK and auto generated FK on through model in Many2Many relations.

False
onupdate Union[ReferentialAction, str, None]

parameter passed to sqlalchemy.ForeignKey. How to treat child rows on update of parent (the one where FK is defined) model.

None
ondelete Union[ReferentialAction, str, None]

parameter passed to sqlalchemy.ForeignKey. How to treat child rows on delete of parent (the one where FK is defined) model.

None
foreign_key_name Optional[str]

optional override for the foreign key constraint name generated in migrations. Useful when the auto-generated name exceeds a database specific identifier length limit (for example MySQL 64 chars).

None
kwargs Any

all other args to be populated by BaseField

{}

Returns:

Type Description
ForeignKeyField

ormar ForeignKeyField with relation to selected model

Source code in ormar/fields/foreign_key.py
Python
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
def ForeignKey(  # type: ignore # noqa CFQ002
    to: Union[type["T"], "ForwardRef"],
    *,
    name: Optional[str] = None,
    unique: bool = False,
    nullable: Optional[bool] = None,
    related_name: Optional[str] = None,
    virtual: bool = False,
    onupdate: Union[ReferentialAction, str, None] = None,
    ondelete: Union[ReferentialAction, str, None] = None,
    foreign_key_name: Optional[str] = None,
    **kwargs: Any,
) -> "T":
    """
    Despite a name it's a function that returns constructed ForeignKeyField.
    This function is actually used in model declaration (as ormar.ForeignKey(ToModel)).

    Accepts number of relation setting parameters as well as all BaseField ones.

    :param to: target related ormar Model
    :type to: Model class
    :param name: name of the database field - later called alias
    :type name: str
    :param unique: parameter passed to sqlalchemy.ForeignKey, unique flag
    :type unique: bool
    :param nullable: marks field as optional/ required; defaults to optional,
        and to required for a foreign key in the primary key
    :type nullable: Optional[bool]
    :param related_name: name of reversed FK relation populated for you on to model
    :type related_name: str
    :param virtual: marks if relation is virtual.
    It is for reversed FK and auto generated FK on through model in Many2Many relations.
    :type virtual: bool
    :param onupdate: parameter passed to sqlalchemy.ForeignKey.
    How to treat child rows on update of parent (the one where FK is defined) model.
    :type onupdate: Union[ReferentialAction, str]
    :param ondelete: parameter passed to sqlalchemy.ForeignKey.
    How to treat child rows on delete of parent (the one where FK is defined) model.
    :type ondelete: Union[ReferentialAction, str]
    :param foreign_key_name: optional override for the foreign key constraint name
    generated in migrations. Useful when the auto-generated name exceeds a database
    specific identifier length limit (for example MySQL 64 chars).
    :type foreign_key_name: Optional[str]
    :param kwargs: all other args to be populated by BaseField
    :type kwargs: Any
    :return: ormar ForeignKeyField with relation to selected model
    :rtype: ForeignKeyField
    """

    onupdate = validate_referential_action(action=onupdate)
    ondelete = validate_referential_action(action=ondelete)

    owner = kwargs.pop("owner", None)
    self_reference = kwargs.pop("self_reference", False)

    orders_by = kwargs.pop("orders_by", None)
    related_orders_by = kwargs.pop("related_orders_by", None)

    skip_reverse = kwargs.pop("skip_reverse", False)
    skip_field = kwargs.pop("skip_field", False)

    primary_key = kwargs.pop("primary_key", False)
    if primary_key and nullable:
        raise ModelDefinitionError(
            "A foreign key that is part of the primary key cannot be nullable."
        )
    nullable = (not primary_key) if nullable is None else nullable
    sql_nullable = kwargs.pop("sql_nullable", None)
    sql_nullable = nullable if sql_nullable is None else sql_nullable

    index = kwargs.pop("index", False)
    to_field = kwargs.pop("to_field", None)
    columns = kwargs.pop("columns", None)
    if columns is not None and name is not None:
        raise ModelDefinitionError(
            "Pass either name= (one column) or columns= (column names by "
            "referenced column), not both."
        )
    db_constraint = kwargs.pop("db_constraint", True)
    if not db_constraint and (
        onupdate is not None or ondelete is not None or foreign_key_name is not None
    ):
        raise ModelDefinitionError(
            "ondelete/onupdate/foreign_key_name need a database constraint, they "
            "cannot be used with db_constraint=False."
        )

    validate_not_allowed_fields(kwargs)
    key_only_model = None
    if to.__class__ == ForwardRef:
        __type__ = to if not nullable else Optional[to]
        column_type = None
    else:
        validate_view_target(
            to=to,  # type: ignore
            virtual=virtual,
            db_constraint=db_constraint,
        )
        params = populate_fk_params_based_on_to_model(
            to=to,  # type: ignore
            nullable=nullable,
            virtual=virtual,
            to_field=to_field,
        )
        validate_link_columns(
            to=to,  # type: ignore
            to_field=to_field,
            columns=columns,
            name=name,
        )
        __type__ = params.annotation
        column_type = params.column_type
        key_only_model = params.key_only_model

    namespace = dict(
        __type__=__type__,
        to=to,
        to_key_only=key_only_model,
        through=None,
        alias=name,
        name=kwargs.pop("real_name", None),
        nullable=nullable,
        sql_nullable=sql_nullable,
        unique=unique,
        column_type=column_type,
        related_name=related_name,
        virtual=virtual,
        primary_key=primary_key,
        index=index,
        default=None,
        server_default=None,
        onupdate=onupdate,
        ondelete=ondelete,
        foreign_key_name=foreign_key_name,
        to_field=to_field,
        columns=columns,
        db_constraint=db_constraint,
        owner=owner,
        self_reference=self_reference,
        is_relation=True,
        orders_by=orders_by,
        related_orders_by=related_orders_by,
        skip_reverse=skip_reverse,
        skip_field=skip_field,
        **kwargs,
    )

    Field = type("ForeignKey", (ForeignKeyField, BaseField), {})
    return Field(**namespace)

OneToOne(to, **kwargs)

Python
OneToOne(to: type[T], **kwargs: Any) -> T
Python
OneToOne(to: ForwardRef, **kwargs: Any) -> Model

A foreign key whose related model has at most one model pointing back at it: its column is unique (unless it is the primary key, which already is), and the reverse side holds a single model or None instead of a list. The default reverse name is the owner model name, without the trailing s.

Accepts the same arguments as ForeignKey.

Parameters:

Name Type Description Default
to Union[type[T], ForwardRef]

target related ormar Model

required
kwargs Any

ForeignKey parameters

{}

Returns:

Type Description
ForeignKeyField

ormar ForeignKeyField with a one to one relation

Source code in ormar/fields/foreign_key.py
Python
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
def OneToOne(  # type: ignore
    to: Union[type["T"], "ForwardRef"], **kwargs: Any
) -> "T":
    """
    A foreign key whose related model has at most one model pointing back at it:
    its column is unique (unless it is the primary key, which already is), and
    the reverse side holds a single model or ``None`` instead of a list. The
    default reverse name is the owner model name, without the trailing ``s``.

    Accepts the same arguments as ``ForeignKey``.

    :param to: target related ormar Model
    :type to: Model class
    :param kwargs: ``ForeignKey`` parameters
    :type kwargs: Any
    :return: ormar ForeignKeyField with a one to one relation
    :rtype: ForeignKeyField
    """
    if kwargs.get("unique") is False:
        raise ModelDefinitionError(
            "A OneToOne relation is always unique, use a ForeignKey for a "
            "non-unique relation."
        )
    if not kwargs.get("primary_key"):
        kwargs["unique"] = True
    return cast("T", ForeignKey(to=to, one_to_one=True, **kwargs))

column_type(model, field, column)

Parameters:

Name Type Description Default
model type[Model]

model the column belongs to

required
field str

field of the model storing the column

required
column str

database column

required

Returns:

Type Description
Any

SQLAlchemy type of the column: the field's own type, the type of the referenced column for a foreign key

Source code in ormar/fields/foreign_key.py
Python
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
def column_type(model: type["Model"], field: str, column: str) -> Any:
    """
    :param model: model the column belongs to
    :type model: type[Model]
    :param field: field of the model storing the column
    :type field: str
    :param column: database column
    :type column: str
    :return: SQLAlchemy type of the column: the field's own type, the type
        of the referenced column for a foreign key
    :rtype: Any
    """
    model_field = model.ormar_config.model_fields[field]
    if not model_field.is_relation:
        return model_field.column_type
    pair = next(
        pair
        for pair in cast("ForeignKeyField", model_field).link.pairs
        if pair.source_column == column
    )
    return column_type(
        model=model_field.to, field=pair.target_field, column=pair.target_column
    )

flat_field_from_columns(model, field, values)

Parameters:

Name Type Description Default
model type[Model]

model the field belongs to

required
field str

referenced field

required
values dict[str, Any]

values of the model's columns by column name

required

Returns:

Type Description
Any

the field's value in flattened output: a relation's own flattened value (see ForeignKeyField.flat_from_columns), else the value of its column

Source code in ormar/fields/foreign_key.py
Python
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
def flat_field_from_columns(
    model: type["Model"], field: str, values: dict[str, Any]
) -> Any:
    """
    :param model: model the field belongs to
    :type model: type[Model]
    :param field: referenced field
    :type field: str
    :param values: values of the model's columns by column name
    :type values: dict[str, Any]
    :return: the field's value in flattened output: a relation's own
        flattened value (see ``ForeignKeyField.flat_from_columns``), else the
        value of its column
    :rtype: Any
    """
    model_field = model.ormar_config.model_fields[field]
    if not model_field.is_relation:
        return values[model.get_column_alias(field_name=field)]
    relation = cast("ForeignKeyField", model_field)
    return relation.flat_from_columns(
        values={
            pair.target_column: values[pair.source_column]
            for pair in relation.link.pairs
        }
    )

flat_field_type(model, field)

Parameters:

Name Type Description Default
model type[Model]

model the field belongs to

required
field str

referenced field

required

Returns:

Type Description
Any

python type of the field in flattened output (see flat_field_from_columns)

Source code in ormar/fields/foreign_key.py
Python
192
193
194
195
196
197
198
199
200
201
202
203
204
205
def flat_field_type(model: type["Model"], field: str) -> Any:
    """
    :param model: model the field belongs to
    :type model: type[Model]
    :param field: referenced field
    :type field: str
    :return: python type of the field in flattened output (see
        ``flat_field_from_columns``)
    :rtype: Any
    """
    model_field = model.ormar_config.model_fields[field]
    if model_field.is_relation:
        return cast("ForeignKeyField", model_field).flat_value_type()
    return model_field.__type__

populate_fk_params_based_on_to_model(*, to, nullable, virtual, to_field=None)

Based on target to model to which relation leads to populates the type of the pydantic field to use and the type of the referencing column.

Parameters:

Name Type Description Default
to type[T]

target related ormar Model

required
nullable bool

marks field as optional/ required

required
virtual bool

whether the field is a reverse relation holding no column

required
to_field Union[str, list[str], tuple[str, ...], None]

unique field(s) of the target referenced instead of its pk

None

Returns:

Type Description
FkParams

annotation, column type and key-only model of the relation

Source code in ormar/fields/foreign_key.py
Python
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
def populate_fk_params_based_on_to_model(
    *,
    to: type["T"],
    nullable: bool,
    virtual: bool,
    to_field: Union[str, list[str], tuple[str, ...], None] = None,
) -> FkParams:
    """
    Based on target to model to which relation leads to populates the type of the
    pydantic field to use and the type of the referencing column.

    :param to: target related ormar Model
    :type to: Model class
    :param nullable: marks field as optional/ required
    :type nullable: bool
    :param virtual: whether the field is a reverse relation holding no column
    :type virtual: bool
    :param to_field: unique field(s) of the target referenced instead of its pk
    :type to_field: Union[str, list[str], tuple[str, ...], None]
    :return: annotation, column type and key-only model of the relation
    :rtype: FkParams
    """
    key = to.ormar_config.pk
    names = to_field_names(to_field=to_field)
    if names is None:
        target_fields = key.fields
        value_type = key.python_type()
    else:
        validate_to_field(to=to, fields=names)
        target_fields = names
        value_type = (
            to.ormar_config.model_fields[names[0]].__type__
            if len(names) == 1
            else tuple
        )
    target_field = to.ormar_config.model_fields[target_fields[0]]
    key_only_model = key_only_model_type(target=to, fields=target_fields)
    annotation = (
        Union[value_type, to, key_only_model]
        if not nullable
        else Optional[Union[value_type, to, key_only_model]]
    )
    return FkParams(
        annotation=annotation,
        column_type=target_field.column_type,
        key_only_model=key_only_model,
    )

referenced_columns(to, to_field)

Parameters:

Name Type Description Default
to type[Model]

target model

required
to_field Union[str, list[str], tuple[str, ...], None]

referenced field(s), None for the primary key

required

Returns:

Type Description
dict[str, str]

database columns of the target a foreign key references, each with the target field storing it: the to_field columns or the primary key columns (a key holding foreign keys contributes their columns, each shared column once)

Source code in ormar/fields/foreign_key.py
Python
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
def referenced_columns(
    to: type["Model"], to_field: Union[str, list[str], tuple[str, ...], None]
) -> dict[str, str]:
    """
    :param to: target model
    :type to: type[Model]
    :param to_field: referenced field(s), ``None`` for the primary key
    :type to_field: Union[str, list[str], tuple[str, ...], None]
    :return: database columns of the target a foreign key references, each
        with the target field storing it: the ``to_field`` columns or the
        primary key columns (a key holding foreign keys contributes their
        columns, each shared column once)
    :rtype: dict[str, str]
    """
    names = to_field_names(to_field=to_field)
    if names is None:
        layout = to.ormar_config.pk.layout()
        return dict(zip(layout.column_aliases, layout.column_fields))
    return {to.get_column_alias(field_name=name): name for name in names}

to_field_names(to_field)

Parameters:

Name Type Description Default
to_field Union[str, list[str], tuple[str, ...], None]

to_field as given: one field name or several

required

Returns:

Type Description
Optional[tuple[str, ...]]

the referenced field names as a tuple, None for the primary key

Source code in ormar/fields/foreign_key.py
Python
54
55
56
57
58
59
60
61
62
63
64
65
66
67
def to_field_names(
    to_field: Union[str, list[str], tuple[str, ...], None],
) -> Optional[tuple[str, ...]]:
    """
    :param to_field: ``to_field`` as given: one field name or several
    :type to_field: Union[str, list[str], tuple[str, ...], None]
    :return: the referenced field names as a tuple, ``None`` for the primary key
    :rtype: Optional[tuple[str, ...]]
    """
    if to_field is None:
        return None
    if isinstance(to_field, str):
        return (to_field,)
    return tuple(to_field)

Validate the column options of a foreign key against the columns it references.

Parameters:

Name Type Description Default
to type[Model]

target model

required
to_field Union[str, list[str], tuple[str, ...], None]

referenced field(s), None for the primary key

required
columns Optional[dict[str, str]]

local column names by referenced column

required
name Optional[str]

single local column name

required

Raises:

Type Description
ModelDefinitionError

if columns= doesn't map exactly the referenced columns or name= is used for several columns

Source code in ormar/fields/foreign_key.py
Python
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
def validate_link_columns(
    to: type["Model"],
    to_field: Union[str, list[str], tuple[str, ...], None],
    columns: Optional[dict[str, str]],
    name: Optional[str],
) -> None:
    """
    Validate the column options of a foreign key against the columns it
    references.

    :raises ModelDefinitionError: if ``columns=`` doesn't map exactly the
        referenced columns or ``name=`` is used for several columns
    :param to: target model
    :type to: type[Model]
    :param to_field: referenced field(s), ``None`` for the primary key
    :type to_field: Union[str, list[str], tuple[str, ...], None]
    :param columns: local column names by referenced column
    :type columns: Optional[dict[str, str]]
    :param name: single local column name
    :type name: Optional[str]
    """
    referenced = set(referenced_columns(to=to, to_field=to_field))
    if columns is not None and set(columns) != referenced:
        raise ModelDefinitionError(
            f"columns= must map every referenced column of {to.__name__} "
            f"({sorted(referenced)}) to a column name, got {sorted(columns)}."
        )
    if len(referenced) == 1 and columns is not None:
        raise ModelDefinitionError(
            f"columns= is for foreign keys to several columns of {to.__name__}, "
            "use name= to name the column."
        )
    if len(referenced) > 1 and name is not None:
        raise ModelDefinitionError(
            f"A foreign key to several columns of {to.__name__} needs columns= "
            "instead of name=."
        )

validate_not_allowed_fields(kwargs)

Verifies if not allowed parameters are set on relation models. Usually they are omitted later anyway but this way it's explicitly notify the user that it's not allowed/ supported.

Parameters:

Name Type Description Default
kwargs dict

dict of kwargs to verify passed to relation field

required

Raises:

Type Description
ModelDefinitionError

if any forbidden field is set

Source code in ormar/fields/foreign_key.py
Python
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
def validate_not_allowed_fields(kwargs: dict) -> None:
    """
    Verifies if not allowed parameters are set on relation models.
    Usually they are omitted later anyway but this way it's explicitly
    notify the user that it's not allowed/ supported.

    :raises ModelDefinitionError: if any forbidden field is set
    :param kwargs: dict of kwargs to verify passed to relation field
    :type kwargs: dict
    """
    default = kwargs.pop("default", None)
    encrypt_secret = kwargs.pop("encrypt_secret", None)
    encrypt_backend = kwargs.pop("encrypt_backend", None)
    encrypt_custom_backend = kwargs.pop("encrypt_custom_backend", None)
    overwrite_pydantic_type = kwargs.pop("overwrite_pydantic_type", None)

    not_supported = [
        default,
        encrypt_secret,
        encrypt_backend,
        encrypt_custom_backend,
        overwrite_pydantic_type,
    ]
    if any(x is not None for x in not_supported):
        raise ModelDefinitionError(
            f"Argument {next((x for x in not_supported if x is not None))} "
            f"is not supported "
            "on relation fields!"
        )

validate_referential_action(action)

Validation onupdate and ondelete action cast to a string value

Parameters:

Name Type Description Default
action Optional[Union[ReferentialAction, str]]

referential action attribute or name string

required

Raises:

Type Description
ModelDefinitionError

if action is a not valid name string value

Source code in ormar/fields/foreign_key.py
Python
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
def validate_referential_action(
    action: Optional[Union[ReferentialAction, str]],
) -> Optional[str]:
    """
    Validation `onupdate` and `ondelete` action cast to a string value

    :raises ModelDefinitionError: if action is a not valid name string value
    :param action: referential action attribute or name string
    :type action: Optional[Union[ReferentialAction, str]]
    :rtype: Optional[str]
    """

    if action is not None and not isinstance(action, ReferentialAction):
        try:
            action = ReferentialAction(action.upper())
        except (ValueError, AttributeError):
            raise ModelDefinitionError(f"{action} ReferentialAction not supported.")

    return action.value if action is not None else None

validate_to_field(to, fields)

Check that to_field names fields identifying one row of the target: its primary key, a unique=True field, or exactly the columns of a unique constraint (UniqueColumns).

Parameters:

Name Type Description Default
to type[Model]

target model

required
fields tuple[str, ...]

referenced field names

required

Raises:

Type Description
ModelDefinitionError

if a field does not exist or the set is not unique

Source code in ormar/fields/foreign_key.py
Python
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
def validate_to_field(to: type["Model"], fields: tuple[str, ...]) -> None:
    """
    Check that ``to_field`` names fields identifying one row of the target: its
    primary key, a ``unique=True`` field, or exactly the columns of a unique
    constraint (``UniqueColumns``).

    :raises ModelDefinitionError: if a field does not exist or the set is not
        unique
    :param to: target model
    :type to: type[Model]
    :param fields: referenced field names
    :type fields: tuple[str, ...]
    """
    model_fields = to.ormar_config.model_fields
    for name in fields:
        field = model_fields.get(name)
        if field is None or field.is_relation:
            raise ModelDefinitionError(
                f"to_field '{name}' is not a column field of {to.__name__}."
            )
    aliases = {model_fields[name].get_alias() for name in fields}
    unique_sets = [
        {column.name for column in constraint.columns}
        for constraint in to.ormar_config.table.constraints
        if isinstance(constraint, sqlalchemy.UniqueConstraint)
    ]
    if not (
        set(to.ormar_config.pk.fields) == set(fields)
        or (len(fields) == 1 and model_fields[fields[0]].unique)
        or aliases in unique_sets
    ):
        raise ModelDefinitionError(
            f"to_field {list(fields)} of {to.__name__} must be unique "
            "(primary key, unique=True or a UniqueColumns constraint)."
        )

validate_view_target(to, virtual, db_constraint)

A database can't enforce a foreign key to a view, so a relation to a model mapped to a view must not create one.

Parameters:

Name Type Description Default
to type[Model]

target model

required
virtual bool

whether the field is a reverse relation holding no column

required
db_constraint bool

whether the foreign key creates a database constraint

required

Raises:

Type Description
ModelDefinitionError

if a foreign key to a view keeps its constraint

Source code in ormar/fields/foreign_key.py
Python
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
def validate_view_target(to: type["Model"], virtual: bool, db_constraint: bool) -> None:
    """
    A database can't enforce a foreign key to a view, so a relation to a model
    mapped to a view must not create one.

    :raises ModelDefinitionError: if a foreign key to a view keeps its constraint
    :param to: target model
    :type to: type[Model]
    :param virtual: whether the field is a reverse relation holding no column
    :type virtual: bool
    :param db_constraint: whether the foreign key creates a database constraint
    :type db_constraint: bool
    """
    if to.ormar_config.view and not virtual and db_constraint:
        raise ModelDefinitionError(
            f"{to.__name__} is a view, a foreign key to it needs db_constraint=False."
        )