db.models.Field

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.

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

Please login to continue.