ForeignKey.on_delete
When an object referenced by a ForeignKey is deleted, Django will emulate the behavior of the SQL constraint specified by the on_delete argument. For example, if you have a nullable ForeignKey and you want it to be set null when the referenced object is deleted:
user = models.ForeignKey(
User,
models.SET_NULL,
blank=True,
null=True,
)
Deprecated since version 1.9: on_delete will become a required argument in Django 2.0. In older versions it defaults to CASCADE.
The possible values for on_delete are found in django.db.models:
-
-
CASCADE[source] -
Cascade deletes. Django emulates the behavior of the SQL constraint ON DELETE CASCADE and also deletes the object containing the ForeignKey.
-
-
-
PROTECT[source] -
Prevent deletion of the referenced object by raising
ProtectedError, a subclass ofdjango.db.IntegrityError.
-
-
-
SET_NULL[source] -
Set the
ForeignKeynull; this is only possible ifnullisTrue.
-
-
-
SET_DEFAULT[source] -
Set the
ForeignKeyto its default value; a default for theForeignKeymust be set.
-
-
-
SET()[source] -
Set the
ForeignKeyto the value passed toSET(), or if a callable is passed in, the result of calling it. In most cases, passing a callable will be necessary to avoid executing queries at the time your models.py is imported:from django.conf import settings from django.contrib.auth import get_user_model from django.db import models def get_sentinel_user(): return get_user_model().objects.get_or_create(username='deleted')[0] class MyModel(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.SET(get_sentinel_user), )
-
-
-
DO_NOTHING[source] -
Take no action. If your database backend enforces referential integrity, this will cause an
IntegrityErrorunless you manually add an SQLON DELETEconstraint to the database field.
-
-
ForeignKey.limit_choices_to -
Sets a limit to the available choices for this field when this field is rendered using a
ModelFormor the admin (by default, all objects in the queryset are available to choose). Either a dictionary, aQobject, or a callable returning a dictionary orQobject can be used.For example:
staff_member = models.ForeignKey( User, on_delete=models.CASCADE, limit_choices_to={'is_staff': True}, )causes the corresponding field on the
ModelFormto list onlyUsersthat haveis_staff=True. This may be helpful in the Django admin.The callable form can be helpful, for instance, when used in conjunction with the Python
datetimemodule to limit selections by date range. For example:def limit_pub_date_choices(): return {'pub_date__lte': datetime.date.utcnow()} limit_choices_to = limit_pub_date_choicesIf
limit_choices_tois or returns aQ object, which is useful for complex queries, then it will only have an effect on the choices available in the admin when the field is not listed inraw_id_fieldsin theModelAdminfor the model.Note
If a callable is used for
limit_choices_to, it will be invoked every time a new form is instantiated. It may also be invoked when a model is validated, for example by management commands or the admin. The admin constructs querysets to validate its form inputs in various edge cases multiple times, so there is a possibility your callable may be invoked several times.
-
ForeignKey.related_name -
The name to use for the relation from the related object back to this one. It’s also the default value for
related_query_name(the name to use for the reverse filter name from the target model). See the related objects documentation for a full explanation and example. Note that you must set this value when defining relations on abstract models; and when you do so some special syntax is available.If you’d prefer Django not to create a backwards relation, set
related_nameto'+'or end it with'+'. For example, this will ensure that theUsermodel won’t have a backwards relation to this model:user = models.ForeignKey( User, on_delete=models.CASCADE, related_name='+', )
-
ForeignKey.related_query_name -
The name to use for the reverse filter name from the target model. It defaults to the value of
related_nameordefault_related_nameif set, otherwise it defaults to the name of the model:# Declare the ForeignKey with related_query_name class Tag(models.Model): article = models.ForeignKey( Article, on_delete=models.CASCADE, related_name="tags", related_query_name="tag", ) name = models.CharField(max_length=255) # That's now the name of the reverse filter Article.objects.filter(tag__name="important")Like
related_name,related_query_namesupports app label and class interpolation via some special syntax.
-
ForeignKey.to_field -
The field on the related object that the relation is to. By default, Django uses the primary key of the related object.
-
ForeignKey.db_constraint -
Controls whether or not a constraint should be created in the database for this foreign key. The default is
True, and that’s almost certainly what you want; setting this toFalsecan be very bad for data integrity. That said, here are some scenarios where you might want to do this:- You have legacy data that is not valid.
- You’re sharding your database.
If this is set to
False, accessing a related object that doesn’t exist will raise itsDoesNotExistexception.
-
ForeignKey.swappable -
Controls the migration framework’s reaction if this
ForeignKeyis pointing at a swappable model. If it isTrue- the default - then if theForeignKeyis pointing at a model which matches the current value ofsettings.AUTH_USER_MODEL(or another swappable model setting) the relationship will be stored in the migration using a reference to the setting, not to the model directly.You only want to override this to be
Falseif you are sure your model should always point towards the swapped-in model - for example, if it is a profile model designed specifically for your custom user model.Setting it to
Falsedoes not mean you can reference a swappable model even if it is swapped out -Falsejust means that the migrations made with this ForeignKey will always reference the exact model you specify (so it will fail hard if the user tries to run with a User model you don’t support, for example).If in doubt, leave it to its default of
True.
ManyToManyField
-
class ManyToManyField(othermodel, **options)[source]
A many-to-many relationship. Requires a positional argument: the class to which the model is related, which works exactly the same as it does for ForeignKey, including recursive and lazy relationships.
Related objects can be added, removed, or created with the field’s RelatedManager.
Database Representation
Behind the scenes, Django creates an intermediary join table to represent the many-to-many relationship. By default, this table name is generated using the name of the many-to-many field and the name of the table for the model that contains it. Since some databases don’t support table names above a certain length, these table names will be automatically truncated to 64 characters and a uniqueness hash will be used. This means you might see table names like author_books_9cdf4; this is perfectly normal. You can manually provide the name of the join table using the db_table option.
Arguments
ManyToManyField accepts an extra set of arguments – all optional – that control how the relationship functions.
-
ManyToManyField.related_name -
Same as
ForeignKey.related_name.
-
ManyToManyField.related_query_name -
Same as
ForeignKey.related_query_name.
-
ManyToManyField.limit_choices_to -
Same as
ForeignKey.limit_choices_to.limit_choices_tohas no effect when used on aManyToManyFieldwith a custom intermediate table specified using thethroughparameter.
-
ManyToManyField.symmetrical -
Only used in the definition of ManyToManyFields on self. Consider the following model:
from django.db import models class Person(models.Model): friends = models.ManyToManyField("self")When Django processes this model, it identifies that it has a
ManyToManyFieldon itself, and as a result, it doesn’t add aperson_setattribute to thePersonclass. Instead, theManyToManyFieldis assumed to be symmetrical – that is, if I am your friend, then you are my friend.If you do not want symmetry in many-to-many relationships with
self, setsymmetricaltoFalse. This will force Django to add the descriptor for the reverse relationship, allowingManyToManyFieldrelationships to be non-symmetrical.
-
ManyToManyField.through -
Django will automatically generate a table to manage many-to-many relationships. However, if you want to manually specify the intermediary table, you can use the
throughoption to specify the Django model that represents the intermediate table that you want to use.The most common use for this option is when you want to associate extra data with a many-to-many relationship.
If you don’t specify an explicit
throughmodel, there is still an implicitthroughmodel class you can use to directly access the table created to hold the association. It has three fields to link the models.If the source and target models differ, the following fields are generated:
-
id: the primary key of the relation. -
<containing_model>_id: theidof the model that declares theManyToManyField. -
<other_model>_id: theidof the model that theManyToManyFieldpoints to.
If the
ManyToManyFieldpoints from and to the same model, the following fields are generated:-
id: the primary key of the relation. -
from_<model>_id: theidof the instance which points at the model (i.e. the source instance). -
to_<model>_id: theidof the instance to which the relationship points (i.e. the target model instance).
This class can be used to query associated records for a given model instance like a normal model.
-
-
ManyToManyField.through_fields -
Only used when a custom intermediary model is specified. Django will normally determine which fields of the intermediary model to use in order to establish a many-to-many relationship automatically. However, consider the following models:
from django.db import models class Person(models.Model): name = models.CharField(max_length=50) class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField( Person, through='Membership', through_fields=('group', 'person'), ) class Membership(models.Model): group = models.ForeignKey(Group, on_delete=models.CASCADE) person = models.ForeignKey(Person, on_delete=models.CASCADE) inviter = models.ForeignKey( Person, on_delete=models.CASCADE, related_name="membership_invites", ) invite_reason = models.CharField(max_length=64)Membershiphas two foreign keys toPerson(personandinviter), which makes the relationship ambiguous and Django can’t know which one to use. In this case, you must explicitly specify which foreign keys Django should use usingthrough_fields, as in the example above.through_fieldsaccepts a 2-tuple('field1', 'field2'), wherefield1is the name of the foreign key to the model theManyToManyFieldis defined on (groupin this case), andfield2the name of the foreign key to the target model (personin this case).When you have more than one foreign key on an intermediary model to any (or even both) of the models participating in a many-to-many relationship, you must specify
through_fields. This also applies to recursive relationships when an intermediary model is used and there are more than two foreign keys to the model, or you want to explicitly specify which two Django should use.Recursive relationships using an intermediary model are always defined as non-symmetrical – that is, with
symmetrical=False– therefore, there is the concept of a “source” and a “target”. In that case'field1'will be treated as the “source” of the relationship and'field2'as the “target”.
-
ManyToManyField.db_table -
The name of the table to create for storing the many-to-many data. If this is not provided, Django will assume a default name based upon the names of: the table for the model defining the relationship and the name of the field itself.
-
ManyToManyField.db_constraint -
Controls whether or not constraints should be created in the database for the foreign keys in the intermediary table. The default is
True, and that’s almost certainly what you want; setting this toFalsecan be very bad for data integrity. That said, here are some scenarios where you might want to do this:- You have legacy data that is not valid.
- You’re sharding your database.
It is an error to pass both
db_constraintandthrough.
-
ManyToManyField.swappable -
Controls the migration framework’s reaction if this
ManyToManyFieldis pointing at a swappable model. If it isTrue- the default - then if theManyToManyFieldis pointing at a model which matches the current value ofsettings.AUTH_USER_MODEL(or another swappable model setting) the relationship will be stored in the migration using a reference to the setting, not to the model directly.You only want to override this to be
Falseif you are sure your model should always point towards the swapped-in model - for example, if it is a profile model designed specifically for your custom user model.If in doubt, leave it to its default of
True.
ManyToManyField does not support validators.
null has no effect since there is no way to require a relationship at the database level.
OneToOneField
-
class OneToOneField(othermodel, on_delete, parent_link=False, **options)[source]
A one-to-one relationship. Conceptually, this is similar to a ForeignKey with unique=True, but the “reverse” side of the relation will directly return a single object.
on_delete can now be used as the second positional argument (previously it was typically only passed as a keyword argument). It will be a required argument in Django 2.0.
This is most useful as the primary key of a model which “extends” another model in some way; Multi-table inheritance is implemented by adding an implicit one-to-one relation from the child model to the parent model, for example.
One positional argument is required: the class to which the model will be related. This works exactly the same as it does for ForeignKey, including all the options regarding recursive and lazy relationships.
If you do not specify the related_name argument for the OneToOneField, Django will use the lower-case name of the current model as default value.
With the following example:
from django.conf import settings
from django.db import models
class MySpecialUser(models.Model):
user = models.OneToOneField(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
)
supervisor = models.OneToOneField(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
related_name='supervisor_of',
)
your resulting User model will have the following attributes:
>>> user = User.objects.get(pk=1) >>> hasattr(user, 'myspecialuser') True >>> hasattr(user, 'supervisor_of') True
A DoesNotExist exception is raised when accessing the reverse relationship if an entry in the related table doesn’t exist. For example, if a user doesn’t have a supervisor designated by MySpecialUser:
>>> user.supervisor_of
Traceback (most recent call last):
...
DoesNotExist: User matching query does not exist.
Additionally, OneToOneField accepts all of the extra arguments accepted by ForeignKey, plus one extra argument:
-
OneToOneField.parent_link -
When
Trueand used in a model which inherits from another concrete model, indicates that this field should be used as the link back to the parent class, rather than the extraOneToOneFieldwhich would normally be implicitly created by subclassing.
See One-to-one relationships for usage examples of OneToOneField.
Field API reference
-
class Field[source] -
Fieldis an abstract class that represents a database table column. Django uses fields to create the database table (db_type()), to map Python types to database (get_prep_value()) and vice-versa (from_db_value()).A field is thus a fundamental piece in different Django APIs, notably,
modelsandquerysets.In models, a field is instantiated as a class attribute and represents a particular table column, see Models. It has attributes such as
nullandunique, and methods that Django uses to map the field value to database-specific values.A
Fieldis a subclass ofRegisterLookupMixinand thus bothTransformandLookupcan be registered on it to be used inQuerySets (e.g.field_name__exact="foo"). All built-in lookups are registered by default.All of Django’s built-in fields, such as
CharField, are particular implementations ofField. If you need a custom field, you can either subclass any of the built-in fields or write aFieldfrom scratch. In either case, see Writing custom model fields.-
description -
A verbose description of the field, e.g. for the
django.contrib.admindocsapplication.The description can be of the form:
description = _("String (up to %(max_length)s)")where the arguments are interpolated from the field’s
__dict__.
To map a
Fieldto a database-specific type, Django exposes several methods:-
get_internal_type()[source] -
Returns a string naming this field for backend specific purposes. By default, it returns the class name.
See Emulating built-in field types for usage in custom fields.
-
db_type(connection)[source] -
Returns the database column data type for the
Field, taking into account theconnection.See Custom database types for usage in custom fields.
-
rel_db_type(connection)[source] -
New in Django 1.10.
Returns the database column data type for fields such as
ForeignKeyandOneToOneFieldthat point to theField, taking into account theconnection.See Custom database types for usage in custom fields.
There are three main situations where Django needs to interact with the database backend and fields:
- when it queries the database (Python value -> database backend value)
- when it loads data from the database (database backend value -> Python value)
- when it saves to the database (Python value -> database backend value)
When querying,
get_db_prep_value()andget_prep_value()are used:-
get_prep_value(value)[source] -
valueis the current value of the model’s attribute, and the method should return data in a format that has been prepared for use as a parameter in a query.See Converting Python objects to query values for usage.
-
get_db_prep_value(value, connection, prepared=False)[source] -
Converts
valueto a backend-specific value. By default it returnsvalueifprepared=Trueandget_prep_value()if isFalse.See Converting query values to database values for usage.
When loading data,
from_db_value()is used:-
from_db_value(value, expression, connection, context) -
Converts a value as returned by the database to a Python object. It is the reverse of
get_prep_value().This method is not used for most built-in fields as the database backend already returns the correct Python type, or the backend itself does the conversion.
See Converting values to Python objects for usage.
Note
For performance reasons,
from_db_valueis not implemented as a no-op on fields which do not require it (all Django fields). Consequently you may not callsuperin your definition.
When saving,
pre_save()andget_db_prep_save()are used:-
get_db_prep_save(value, connection)[source] -
Same as the
get_db_prep_value(), but called when the field value must be saved to the database. By default returnsget_db_prep_value().
-
pre_save(model_instance, add)[source] -
Method called prior to
get_db_prep_save()to prepare the value before being saved (e.g. forDateField.auto_now).model_instanceis the instance this field belongs to andaddis whether the instance is being saved to the database for the first time.It should return the value of the appropriate attribute from
model_instancefor this field. The attribute name is inself.attname(this is set up byField).See Preprocessing values before saving for usage.
Fields often receive their values as a different type, either from serialization or from forms.
-
to_python(value)[source] -
Converts the value into the correct Python object. It acts as the reverse of
value_to_string(), and is also called inclean().See Converting values to Python objects for usage.
Besides saving to the database, the field also needs to know how to serialize its value:
-
value_to_string(obj)[source] -
Converts
objto a string. Used to serialize the value of the field.See Converting field data for serialization for usage.
When using
model forms, theFieldneeds to know which form field it should be represented by:-
formfield(form_class=None, choices_form_class=None, **kwargs)[source] -
Returns the default
django.forms.Fieldof this field forModelForm.By default, if both
form_classandchoices_form_classareNone, it usesCharField. If the field haschoicesandchoices_form_classisn’t specified, it usesTypedChoiceField.See Specifying the form field for a model field for usage.
-
deconstruct()[source] -
Returns a 4-tuple with enough information to recreate the field:
- The name of the field on the model.
- The import path of the field (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.
This method must be added to fields prior to 1.7 to migrate its data using Migrations.
-
Every Field instance contains several attributes that allow introspecting its behavior. Use these attributes instead of isinstance checks when you need to write code that depends on a field’s functionality. These attributes can be used together with the Model._meta API to narrow down a search for specific field types. Custom model fields should implement these flags.
Attributes for fields
-
Field.auto_created -
Boolean flag that indicates if the field was automatically created, such as the
OneToOneFieldused by model inheritance.
-
Field.concrete -
Boolean flag that indicates if the field has a database column associated with it.
-
Field.hidden -
Boolean flag that indicates if a field is used to back another non-hidden field’s functionality (e.g. the
content_typeandobject_idfields that make up aGenericForeignKey). Thehiddenflag is used to distinguish what constitutes the public subset of fields on the model from all the fields on the model.Note
Options.get_fields()excludes hidden fields by default. Pass ininclude_hidden=Trueto return hidden fields in the results.
-
Field.is_relation -
Boolean flag that indicates if a field contains references to one or more other models for its functionality (e.g.
ForeignKey,ManyToManyField,OneToOneField, etc.).
-
Field.model -
Returns the model on which the field is defined. If a field is defined on a superclass of a model,
modelwill refer to the superclass, not the class of the instance.
Attributes for fields with relations
These attributes are used to query for the cardinality and other details of a relation. These attribute are present on all fields; however, they will only have boolean values (rather than None) if the field is a relation type (Field.is_relation=True).
-
Field.many_to_many -
Boolean flag that is
Trueif the field has a many-to-many relation;Falseotherwise. The only field included with Django where this isTrueisManyToManyField.
-
Field.many_to_one -
Boolean flag that is
Trueif the field has a many-to-one relation, such as aForeignKey;Falseotherwise.
-
Field.one_to_many -
Boolean flag that is
Trueif the field has a one-to-many relation, such as aGenericRelationor the reverse of aForeignKey;Falseotherwise.
-
Field.one_to_one -
Boolean flag that is
Trueif the field has a one-to-one relation, such as aOneToOneField;Falseotherwise.
-
Field.related_model -
Points to the model the field relates to. For example,
AuthorinForeignKey(Author, on_delete=models.CASCADE). If a field has a generic relation (such as aGenericForeignKeyor aGenericRelation) thenrelated_modelwill beNone.
Please login to continue.