class documentation

class ForeignKey(ForeignObject):

Known subclasses: django.db.models.fields.related.OneToOneField

View In Hierarchy

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.

Method __init__ Undocumented
Method ​_check​_on​_delete Undocumented
Method ​_check​_unique Undocumented
Method check Undocumented
Method contribute​_to​_related​_class Undocumented
Method convert​_empty​_strings Undocumented
Method db​_check Return the database column check constraint for this field, for the provided connection. Works the same way as db_type() for the case that get_internal_type() does not map to a preexisting model field.
Method db​_parameters Extension of db_type(), providing a range of different return values (type, checks). This will look at db_type(), allowing custom model fields to override it.
Method db​_type Return the database column data type for this field, for the provided connection.
Method deconstruct Return enough information to recreate the field as a 4-tuple:
Method formfield Pass limit_choices_to to the field being constructed.
Method get​_attname Undocumented
Method get​_attname​_column Undocumented
Method get​_col Undocumented
Method get​_db​_converters Undocumented
Method get​_db​_prep​_save Return field's value prepared for saving into a database.
Method get​_db​_prep​_value Return field's value prepared for interacting with the database backend.
Method get​_default Return the to_field if the default value is an object.
Method get​_prep​_value Perform preliminary non-db specific value checks and conversions.
Method get​_reverse​_path​_info Get path from the related model to this field's model.
Method resolve​_related​_fields Undocumented
Method to​_python Convert the input value into the expected Python data type, raising django.core.exceptions.ValidationError if the data can't be converted. Return the converted value. Subclasses should override this.
Method validate Validate value and raise ValidationError if necessary. Subclasses should override this to provide validation logic.
Class Variable default​_error​_messages Undocumented
Class Variable description Undocumented
Class Variable empty​_strings​_allowed Undocumented
Class Variable many​_to​_many Undocumented
Class Variable many​_to​_one Undocumented
Class Variable one​_to​_many Undocumented
Class Variable one​_to​_one Undocumented
Instance Variable db​_constraint Undocumented
Property target​_field When filtering against this relation, return the field on the remote model against which the filtering should happen.

Inherited from ForeignObject:

Class Method get​_lookups Undocumented
Static Method get​_instance​_value​_for​_fields Undocumented
Method ​_check​_to​_fields​_exist Undocumented
Method ​_check​_unique​_target Undocumented
Method contribute​_to​_class Register the field with the model class it belongs to.
Method get​_extra​_descriptor​_filter Return an extra filter condition for related object fetching when user does 'instance.fieldname', that is the extra filter is used in the descriptor of the field.
Method get​_extra​_restriction Return a pair condition used for joining and subquery pushdown. The condition is something that responds to as_sql(compiler, connection) method.
Method get​_foreign​_related​_value Undocumented
Method get​_joining​_columns Undocumented
Method get​_local​_related​_value Undocumented
Method get​_path​_info Get path from this field to the related model.
Method get​_reverse​_joining​_columns Undocumented
Class Variable requires​_unique​_target Undocumented
Instance Variable from​_fields Undocumented
Instance Variable swappable Undocumented
Instance Variable to​_fields Undocumented
Property foreign​_related​_fields Undocumented
Property local​_related​_fields Undocumented
Property related​_fields Undocumented
Property reverse​_related​_fields Undocumented

Inherited from RelatedField (via ForeignObject):

Method ​_check​_clashes Check accessor and reverse query name clashes.
Method ​_check​_referencing​_to​_swapped​_model Undocumented
Method ​_check​_related​_name​_is​_valid Undocumented
Method ​_check​_related​_query​_name​_is​_valid Undocumented
Method ​_check​_relation​_model​_exists Undocumented
Method do​_related​_class Undocumented
Method get​_cache​_name Undocumented
Method get​_forward​_related​_filter No summary
Method get​_limit​_choices​_to Return limit_choices_to for this model field.
Method get​_reverse​_related​_filter No summary
Method related​_query​_name Define the name that can be used to identify this related object in a table-spanning query.
Method set​_attributes​_from​_rel Undocumented
Instance Variable ​_limit​_choices​_to Undocumented
Instance Variable ​_related​_name Undocumented
Instance Variable ​_related​_query​_name Undocumented
Instance Variable name Undocumented
Instance Variable opts Undocumented
Instance Variable verbose​_name Undocumented
Property related​_model Undocumented
Property swappable​_setting Get the setting that this is powered from for swapping, or None if it's not swapped in / marked with swappable=False.

Inherited from FieldCacheMixin (via ForeignObject, RelatedField):

Method delete​_cached​_value Undocumented
Method get​_cached​_value Undocumented
Method is​_cached Undocumented
Method set​_cached​_value Undocumented

Inherited from Field (via ForeignObject, RelatedField):

Class Method ​_choices​_is​_value Undocumented
Method __copy__ Undocumented
Method __deepcopy__ Undocumented
Method __eq__ Undocumented
Method __hash__ Undocumented
Method __lt__ Undocumented
Method __reduce__ Pickling should return the model._meta.fields instance of the field, not a new copy of that field. So, use the app registry to load the model and then the field back.
Method __repr__ Display the module, class, and name of the field.
Method __str__ Return "app_label.model_label.field_name" for fields attached to models.
Method ​_check​_backend​_specific​_checks Undocumented
Method ​_check​_choices Undocumented
Method ​_check​_db​_index Undocumented
Method ​_check​_deprecation​_details Undocumented
Method ​_check​_field​_name Check if field name is valid, i.e. 1) does not end with an underscore, 2) does not contain "__" and 3) is not "pk".
Method ​_check​_null​_allowed​_for​_primary​_keys Undocumented
Method ​_check​_validators Undocumented
Method ​_description Undocumented
Method ​_get​_flatchoices Flattened version of choices tuple.
Method cast​_db​_type Return the data type to use in the Cast() function.
Method clean Convert the value's type and run validation. Validation errors from to_python() and validate() are propagated. Return the correct value if no error is raised.
Method clone Uses deconstruct() to clone a new copy of this Field. Will not preserve any class attachments/attribute names.
Method db​_type​_parameters Undocumented
Method db​_type​_suffix Undocumented
Method get​_choices Return choices with a default blank choices included, for use as <select> choices for this field.
Method get​_filter​_kwargs​_for​_object Return a dict that when passed as kwargs to self.model.filter(), would yield all instances having the same value for this field as obj has.
Method get​_internal​_type Undocumented
Method get​_pk​_value​_on​_save No summary
Method has​_default Return a boolean of whether this field has a default value.
Method pre​_save Return field's value just before saving.
Method rel​_db​_type Return the data type that a related field pointing to this field should use. For example, this method is called by ForeignKey and OneToOneField to determine its data type.
Method run​_validators Undocumented
Method save​_form​_data Undocumented
Method select​_format Custom format for select clauses. For example, GIS columns need to be selected as AsText(table.col) on MySQL as the table.col data can't be used by Django.
Method set​_attributes​_from​_name Undocumented
Method value​_from​_object Return the value of this field in the given model instance.
Method value​_to​_string Return a string value of this field from the passed obj. This is used by the serialization framework.
Class Variable auto​_creation​_counter Undocumented
Class Variable default​_validators Undocumented
Class Variable empty​_values Undocumented
Class Variable flatchoices Undocumented
Class Variable hidden Undocumented
Class Variable system​_check​_deprecated​_details Undocumented
Class Variable system​_check​_removed​_details Undocumented
Instance Variable ​_db​_tablespace Undocumented
Instance Variable ​_error​_messages Undocumented
Instance Variable ​_unique Undocumented
Instance Variable ​_validators Undocumented
Instance Variable ​_verbose​_name Undocumented
Instance Variable attname Undocumented
Instance Variable auto​_created Undocumented
Instance Variable blank Undocumented
Instance Variable choices Undocumented
Instance Variable column Undocumented
Instance Variable concrete Undocumented
Instance Variable creation​_counter Undocumented
Instance Variable db​_column Undocumented
Instance Variable db​_index Undocumented
Instance Variable default Undocumented
Instance Variable editable Undocumented
Instance Variable error​_messages Undocumented
Instance Variable help​_text Undocumented
Instance Variable is​_relation Undocumented
Instance Variable max​_length Undocumented
Instance Variable model Undocumented
Instance Variable null Undocumented
Instance Variable primary​_key Undocumented
Instance Variable remote​_field Undocumented
Instance Variable serialize Undocumented
Instance Variable unique​_for​_date Undocumented
Instance Variable unique​_for​_month Undocumented
Instance Variable unique​_for​_year Undocumented
Property ​_get​_default Undocumented
Property cached​_col Undocumented
Property db​_returning Private API intended only to be used by Django itself. Currently only the PostgreSQL backend supports returning multiple fields on a model.
Property db​_tablespace Undocumented
Property unique Undocumented
Property validators Some validators can't be created at field initialization time. This method provides a way to delay their creation until required.

Inherited from RegisterLookupMixin (via ForeignObject, RelatedField, Field):

Class Method register​_lookup Undocumented
Static Method merge​_dicts Merge dicts in reverse to preference the order of the original list. e.g., merge_dicts([a, b]) will preference the keys in 'a' over those in 'b'.
Class Method ​_clear​_cached​_lookups Undocumented
Class Method ​_get​_lookup Undocumented
Class Method ​_unregister​_lookup Remove given lookup from cls lookups. For use in tests only as it's not thread-safe.
Method get​_lookup Undocumented
Method get​_transform Undocumented
def __init__(self, to, on_delete, related_name=None, related_query_name=None, limit_choices_to=None, parent_link=False, to_field=None, db_constraint=True, **kwargs):
def _check_on_delete(self):

Undocumented

def _check_unique(self, **kwargs):
def check(self, **kwargs):
def contribute_to_related_class(self, cls, related):
def convert_empty_strings(self, value, expression, connection):

Undocumented

def db_check(self, connection):
Return the database column check constraint for this field, for the provided connection. Works the same way as db_type() for the case that get_internal_type() does not map to a preexisting model field.
def db_parameters(self, connection):
Extension of db_type(), providing a range of different return values (type, checks). This will look at db_type(), allowing custom model fields to override it.
def db_type(self, connection):
Return the database column data type for this field, for the provided connection.
def deconstruct(self):

Return enough information to recreate the field as a 4-tuple:

  • The name of the field on the model, if contribute_to_class() has been run.
  • The import path of the field, including the class, e.g. django.db.models.IntegerField. This should be the most portable version, so less specific may be better.
  • A list of positional arguments.
  • A dict of keyword arguments.

Note that the positional or keyword arguments must contain values of the following types (including inner values of collection types):

  • None, bool, str, int, float, complex, set, frozenset, list, tuple, dict
  • UUID
  • datetime.datetime (naive), datetime.date
  • top-level classes, top-level functions - will be referenced by their full import path
  • Storage instances - these have their own deconstruct() method

This is because the values here must be serialized into a text format (possibly new Python code, possibly JSON) and these are the only types with encoding handlers defined.

There's no need to return the exact way the field was instantiated this time, just ensure that the resulting field is the same - prefer keyword arguments over positional ones, and omit parameters with their default values.

def formfield(self, *, using=None, **kwargs):

Pass limit_choices_to to the field being constructed.

Only passes it if there is a type that supports related fields. This is a similar strategy used to pass the queryset to the field being constructed.

def get_attname(self):
def get_attname_column(self):
def get_col(self, alias, output_field=None):

Undocumented

def get_db_converters(self, connection):
def get_db_prep_save(self, value, connection):
Return field's value prepared for saving into a database.
def get_db_prep_value(self, value, connection, prepared=False):

Return field's value prepared for interacting with the database backend.

Used by the default implementations of get_db_prep_save().

def get_default(self):
Return the to_field if the default value is an object.
def get_prep_value(self, value):
Perform preliminary non-db specific value checks and conversions.
def get_reverse_path_info(self, filtered_relation=None):
Get path from the related model to this field's model.
def resolve_related_fields(self):
def to_python(self, value):
Convert the input value into the expected Python data type, raising django.core.exceptions.ValidationError if the data can't be converted. Return the converted value. Subclasses should override this.
def validate(self, value, model_instance):
Validate value and raise ValidationError if necessary. Subclasses should override this to provide validation logic.
default_error_messages =
empty_strings_allowed: bool =
db_constraint =

Undocumented

@property
target_field =
When filtering against this relation, return the field on the remote model against which the filtering should happen.