Provide a many-to-one relation by adding a column to the local model to hold the remote value. By default ForeignKey will target the pk of the remote model but this behavior can be changed by using the ``to_field`` argument.
| 960 | |
| 961 | |
| 962 | class ForeignKey(ForeignObject): |
| 963 | """ |
| 964 | Provide a many-to-one relation by adding a column to the local model |
| 965 | to hold the remote value. |
| 966 | |
| 967 | By default ForeignKey will target the pk of the remote model but this |
| 968 | behavior can be changed by using the ``to_field`` argument. |
| 969 | """ |
| 970 | |
| 971 | descriptor_class = ForeignKeyDeferredAttribute |
| 972 | # Field flags |
| 973 | many_to_many = False |
| 974 | many_to_one = True |
| 975 | one_to_many = False |
| 976 | one_to_one = False |
| 977 | |
| 978 | rel_class = ManyToOneRel |
| 979 | |
| 980 | empty_strings_allowed = False |
| 981 | default_error_messages = { |
| 982 | "invalid": _( |
| 983 | "%(model)s instance with %(field)s %(value)r is not a valid choice." |
| 984 | ) |
| 985 | } |
| 986 | description = _("Foreign Key (type determined by related field)") |
| 987 | |
| 988 | def __init__( |
| 989 | self, |
| 990 | to, |
| 991 | on_delete, |
| 992 | related_name=None, |
| 993 | related_query_name=None, |
| 994 | limit_choices_to=None, |
| 995 | parent_link=False, |
| 996 | to_field=None, |
| 997 | db_constraint=True, |
| 998 | **kwargs, |
| 999 | ): |
| 1000 | try: |
| 1001 | to._meta.model_name |
| 1002 | except AttributeError: |
| 1003 | if not isinstance(to, str): |
| 1004 | raise TypeError( |
| 1005 | "%s(%r) is invalid. First parameter to ForeignKey must be " |
| 1006 | "either a model, a model name, or the string %r" |
| 1007 | % ( |
| 1008 | self.__class__.__name__, |
| 1009 | to, |
| 1010 | RECURSIVE_RELATIONSHIP_CONSTANT, |
| 1011 | ) |
| 1012 | ) |
| 1013 | else: |
| 1014 | # For backwards compatibility purposes, we need to *try* and set |
| 1015 | # the to_field during FK construction. It won't be guaranteed to |
| 1016 | # be correct until contribute_to_class is called. Refs #12190. |
| 1017 | to_field = to_field or (to._meta.pk and to._meta.pk.name) |
| 1018 | if not callable(on_delete): |
| 1019 | raise TypeError("on_delete must be callable.") |
no outgoing calls