db.models.ForeignKey.on_delete

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 of django.db.IntegrityError.

  • SET_NULL [source]

    Set the ForeignKey null; this is only possible if null is True.

  • SET_DEFAULT [source]

    Set the ForeignKey to its default value; a default for the ForeignKey must be set.

  • SET() [source]

    Set the ForeignKey to the value passed to SET(), 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 IntegrityError unless you manually add an SQL ON DELETE constraint 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 ModelForm or the admin (by default, all objects in the queryset are available to choose). Either a dictionary, a Q object, or a callable returning a dictionary or Q object 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 ModelForm to list only Users that have is_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 datetime module 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_choices

If limit_choices_to is or returns a Q 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 in raw_id_fields in the ModelAdmin for 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_name to '+' or end it with '+'. For example, this will ensure that the User model 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_name or default_related_name if 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_name supports 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 to False can 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 its DoesNotExist exception.

ForeignKey.swappable

Controls the migration framework’s reaction if this ForeignKey is pointing at a swappable model. If it is True - the default - then if the ForeignKey is pointing at a model which matches the current value of settings.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 False if 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 False does not mean you can reference a swappable model even if it is swapped out - False just 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_to has no effect when used on a ManyToManyField with a custom intermediate table specified using the through parameter.

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 ManyToManyField on itself, and as a result, it doesn’t add a person_set attribute to the Person class. Instead, the ManyToManyField is 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, set symmetrical to False. This will force Django to add the descriptor for the reverse relationship, allowing ManyToManyField relationships 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 through option 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 through model, there is still an implicit through model 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: the id of the model that declares the ManyToManyField.
  • <other_model>_id: the id of the model that the ManyToManyField points to.

If the ManyToManyField points from and to the same model, the following fields are generated:

  • id: the primary key of the relation.
  • from_<model>_id: the id of the instance which points at the model (i.e. the source instance).
  • to_<model>_id: the id of 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)

Membership has two foreign keys to Person (person and inviter), 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 using through_fields, as in the example above.

through_fields accepts a 2-tuple ('field1', 'field2'), where field1 is the name of the foreign key to the model the ManyToManyField is defined on (group in this case), and field2 the name of the foreign key to the target model (person in 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 to False can 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_constraint and through.

ManyToManyField.swappable

Controls the migration framework’s reaction if this ManyToManyField is pointing at a swappable model. If it is True - the default - then if the ManyToManyField is pointing at a model which matches the current value of settings.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 False if 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.

Changed in Django 1.9:

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 True and 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 extra OneToOneField which would normally be implicitly created by subclassing.

See One-to-one relationships for usage examples of OneToOneField.

Field API reference

class Field [source]

Field is 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, models and querysets.

In models, a field is instantiated as a class attribute and represents a particular table column, see Models. It has attributes such as null and unique, and methods that Django uses to map the field value to database-specific values.

A Field is a subclass of RegisterLookupMixin and thus both Transform and Lookup can be registered on it to be used in QuerySets (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 of Field. If you need a custom field, you can either subclass any of the built-in fields or write a Field from scratch. In either case, see Writing custom model fields.

description

A verbose description of the field, e.g. for the django.contrib.admindocs application.

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 Field to 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 the connection.

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 ForeignKey and OneToOneField that point to the Field, taking into account the connection.

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() and get_prep_value() are used:

get_prep_value(value) [source]

value is 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 value to a backend-specific value. By default it returns value if prepared=True and get_prep_value() if is False.

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_value is not implemented as a no-op on fields which do not require it (all Django fields). Consequently you may not call super in your definition.

When saving, pre_save() and get_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 returns get_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. for DateField.auto_now).

model_instance is the instance this field belongs to and add is whether the instance is being saved to the database for the first time.

It should return the value of the appropriate attribute from model_instance for this field. The attribute name is in self.attname (this is set up by Field).

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 in clean().

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 obj to a string. Used to serialize the value of the field.

See Converting field data for serialization for usage.

When using model forms, the Field needs 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.Field of this field for ModelForm.

By default, if both form_class and choices_form_class are None, it uses CharField. If the field has choices and choices_form_class isn’t specified, it uses TypedChoiceField.

See Specifying the form field for a model field for usage.

deconstruct() [source]

Returns a 4-tuple with enough information to recreate the field:

  1. The name of the field on the model.
  2. 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.
  3. A list of positional arguments.
  4. 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 OneToOneField used 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_type and object_id fields that make up a GenericForeignKey). The hidden flag 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 in include_hidden=True to 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, model will 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 True if the field has a many-to-many relation; False otherwise. The only field included with Django where this is True is ManyToManyField.

Field.many_to_one

Boolean flag that is True if the field has a many-to-one relation, such as a ForeignKey; False otherwise.

Field.one_to_many

Boolean flag that is True if the field has a one-to-many relation, such as a GenericRelation or the reverse of a ForeignKey; False otherwise.

Field.one_to_one

Boolean flag that is True if the field has a one-to-one relation, such as a OneToOneField; False otherwise.

Field.related_model

Points to the model the field relates to. For example, Author in ForeignKey(Author, on_delete=models.CASCADE). If a field has a generic relation (such as a GenericForeignKey or a GenericRelation) then related_model will be None.

doc_Django
2016-10-09 18:35:40
Comments
Leave a Comment

Please login to continue.