1. =====================
    
  2. Model field reference
    
  3. =====================
    
  4. 
    
  5. .. module:: django.db.models.fields
    
  6.    :synopsis: Built-in field types.
    
  7. 
    
  8. .. currentmodule:: django.db.models
    
  9. 
    
  10. This document contains all the API references of :class:`Field` including the
    
  11. `field options`_ and `field types`_ Django offers.
    
  12. 
    
  13. .. seealso::
    
  14. 
    
  15.     If the built-in fields don't do the trick, you can try `django-localflavor
    
  16.     <https://github.com/django/django-localflavor>`_ (`documentation
    
  17.     <https://django-localflavor.readthedocs.io/>`_), which contains assorted
    
  18.     pieces of code that are useful for particular countries and cultures.
    
  19. 
    
  20.     Also, you can easily :doc:`write your own custom model fields
    
  21.     </howto/custom-model-fields>`.
    
  22. 
    
  23. .. note::
    
  24. 
    
  25.     Technically, these models are defined in :mod:`django.db.models.fields`, but
    
  26.     for convenience they're imported into :mod:`django.db.models`; the standard
    
  27.     convention is to use ``from django.db import models`` and refer to fields as
    
  28.     ``models.<Foo>Field``.
    
  29. 
    
  30. .. _common-model-field-options:
    
  31. 
    
  32. Field options
    
  33. =============
    
  34. 
    
  35. The following arguments are available to all field types. All are optional.
    
  36. 
    
  37. ``null``
    
  38. --------
    
  39. 
    
  40. .. attribute:: Field.null
    
  41. 
    
  42. If ``True``, Django will store empty values as ``NULL`` in the database. Default
    
  43. is ``False``.
    
  44. 
    
  45. Avoid using :attr:`~Field.null` on string-based fields such as
    
  46. :class:`CharField` and :class:`TextField`. If a string-based field has
    
  47. ``null=True``, that means it has two possible values for "no data": ``NULL``,
    
  48. and the empty string. In most cases, it's redundant to have two possible values
    
  49. for "no data;" the Django convention is to use the empty string, not
    
  50. ``NULL``. One exception is when a :class:`CharField` has both ``unique=True``
    
  51. and ``blank=True`` set. In this situation, ``null=True`` is required to avoid
    
  52. unique constraint violations when saving multiple objects with blank values.
    
  53. 
    
  54. For both string-based and non-string-based fields, you will also need to
    
  55. set ``blank=True`` if you wish to permit empty values in forms, as the
    
  56. :attr:`~Field.null` parameter only affects database storage
    
  57. (see :attr:`~Field.blank`).
    
  58. 
    
  59. .. note::
    
  60. 
    
  61.     When using the Oracle database backend, the value ``NULL`` will be stored to
    
  62.     denote the empty string regardless of this attribute.
    
  63. 
    
  64. ``blank``
    
  65. ---------
    
  66. 
    
  67. .. attribute:: Field.blank
    
  68. 
    
  69. If ``True``, the field is allowed to be blank. Default is ``False``.
    
  70. 
    
  71. Note that this is different than :attr:`~Field.null`. :attr:`~Field.null` is
    
  72. purely database-related, whereas :attr:`~Field.blank` is validation-related. If
    
  73. a field has ``blank=True``, form validation will allow entry of an empty value.
    
  74. If a field has ``blank=False``, the field will be required.
    
  75. 
    
  76. .. admonition:: Supplying missing values
    
  77. 
    
  78.     ``blank=True`` can be used with fields having ``null=False``, but this will
    
  79.     require implementing :meth:`~django.db.models.Model.clean` on the model in
    
  80.     order to programmatically supply any missing values.
    
  81. 
    
  82. .. _field-choices:
    
  83. 
    
  84. ``choices``
    
  85. -----------
    
  86. 
    
  87. .. attribute:: Field.choices
    
  88. 
    
  89. A :term:`sequence` consisting itself of iterables of exactly two items (e.g.
    
  90. ``[(A, B), (A, B) ...]``) to use as choices for this field. If choices are
    
  91. given, they're enforced by :ref:`model validation <validating-objects>` and the
    
  92. default form widget will be a select box with these choices instead of the
    
  93. standard text field.
    
  94. 
    
  95. The first element in each tuple is the actual value to be set on the model,
    
  96. and the second element is the human-readable name. For example::
    
  97. 
    
  98.     YEAR_IN_SCHOOL_CHOICES = [
    
  99.         ('FR', 'Freshman'),
    
  100.         ('SO', 'Sophomore'),
    
  101.         ('JR', 'Junior'),
    
  102.         ('SR', 'Senior'),
    
  103.         ('GR', 'Graduate'),
    
  104.     ]
    
  105. 
    
  106. Generally, it's best to define choices inside a model class, and to
    
  107. define a suitably-named constant for each value::
    
  108. 
    
  109.     from django.db import models
    
  110. 
    
  111.     class Student(models.Model):
    
  112.         FRESHMAN = 'FR'
    
  113.         SOPHOMORE = 'SO'
    
  114.         JUNIOR = 'JR'
    
  115.         SENIOR = 'SR'
    
  116.         GRADUATE = 'GR'
    
  117.         YEAR_IN_SCHOOL_CHOICES = [
    
  118.             (FRESHMAN, 'Freshman'),
    
  119.             (SOPHOMORE, 'Sophomore'),
    
  120.             (JUNIOR, 'Junior'),
    
  121.             (SENIOR, 'Senior'),
    
  122.             (GRADUATE, 'Graduate'),
    
  123.         ]
    
  124.         year_in_school = models.CharField(
    
  125.             max_length=2,
    
  126.             choices=YEAR_IN_SCHOOL_CHOICES,
    
  127.             default=FRESHMAN,
    
  128.         )
    
  129. 
    
  130.         def is_upperclass(self):
    
  131.             return self.year_in_school in {self.JUNIOR, self.SENIOR}
    
  132. 
    
  133. Though you can define a choices list outside of a model class and then
    
  134. refer to it, defining the choices and names for each choice inside the
    
  135. model class keeps all of that information with the class that uses it,
    
  136. and helps reference the choices (e.g, ``Student.SOPHOMORE``
    
  137. will work anywhere that the ``Student`` model has been imported).
    
  138. 
    
  139. .. _field-choices-named-groups:
    
  140. 
    
  141. You can also collect your available choices into named groups that can
    
  142. be used for organizational purposes::
    
  143. 
    
  144.     MEDIA_CHOICES = [
    
  145.         ('Audio', (
    
  146.                 ('vinyl', 'Vinyl'),
    
  147.                 ('cd', 'CD'),
    
  148.             )
    
  149.         ),
    
  150.         ('Video', (
    
  151.                 ('vhs', 'VHS Tape'),
    
  152.                 ('dvd', 'DVD'),
    
  153.             )
    
  154.         ),
    
  155.         ('unknown', 'Unknown'),
    
  156.     ]
    
  157. 
    
  158. The first element in each tuple is the name to apply to the group. The
    
  159. second element is an iterable of 2-tuples, with each 2-tuple containing
    
  160. a value and a human-readable name for an option. Grouped options may be
    
  161. combined with ungrouped options within a single list (such as the
    
  162. ``'unknown'`` option in this example).
    
  163. 
    
  164. For each model field that has :attr:`~Field.choices` set, Django will add a
    
  165. method to retrieve the human-readable name for the field's current value. See
    
  166. :meth:`~django.db.models.Model.get_FOO_display` in the database API
    
  167. documentation.
    
  168. 
    
  169. Note that choices can be any sequence object -- not necessarily a list or
    
  170. tuple. This lets you construct choices dynamically. But if you find yourself
    
  171. hacking :attr:`~Field.choices` to be dynamic, you're probably better off using
    
  172. a proper database table with a :class:`ForeignKey`. :attr:`~Field.choices` is
    
  173. meant for static data that doesn't change much, if ever.
    
  174. 
    
  175. .. note::
    
  176.     A new migration is created each time the order of ``choices`` changes.
    
  177. 
    
  178. .. _field-choices-blank-label:
    
  179. 
    
  180. Unless :attr:`blank=False<Field.blank>` is set on the field along with a
    
  181. :attr:`~Field.default` then a label containing ``"---------"`` will be rendered
    
  182. with the select box. To override this behavior, add a tuple to ``choices``
    
  183. containing ``None``; e.g. ``(None, 'Your String For Display')``.
    
  184. Alternatively, you can use an empty string instead of ``None`` where this makes
    
  185. sense - such as on a :class:`~django.db.models.CharField`.
    
  186. 
    
  187. .. _field-choices-enum-types:
    
  188. 
    
  189. Enumeration types
    
  190. ~~~~~~~~~~~~~~~~~
    
  191. 
    
  192. In addition, Django provides enumeration types that you can subclass to define
    
  193. choices in a concise way::
    
  194. 
    
  195.     from django.utils.translation import gettext_lazy as _
    
  196. 
    
  197.     class Student(models.Model):
    
  198. 
    
  199.         class YearInSchool(models.TextChoices):
    
  200.             FRESHMAN = 'FR', _('Freshman')
    
  201.             SOPHOMORE = 'SO', _('Sophomore')
    
  202.             JUNIOR = 'JR', _('Junior')
    
  203.             SENIOR = 'SR', _('Senior')
    
  204.             GRADUATE = 'GR', _('Graduate')
    
  205. 
    
  206.         year_in_school = models.CharField(
    
  207.             max_length=2,
    
  208.             choices=YearInSchool.choices,
    
  209.             default=YearInSchool.FRESHMAN,
    
  210.         )
    
  211. 
    
  212.         def is_upperclass(self):
    
  213.             return self.year_in_school in {
    
  214.                 self.YearInSchool.JUNIOR,
    
  215.                 self.YearInSchool.SENIOR,
    
  216.             }
    
  217. 
    
  218. These work similar to :mod:`enum` from Python's standard library, but with some
    
  219. modifications:
    
  220. 
    
  221. * Enum member values are a tuple of arguments to use when constructing the
    
  222.   concrete data type. Django supports adding an extra string value to the end
    
  223.   of this tuple to be used as the human-readable name, or ``label``. The
    
  224.   ``label`` can be a lazy translatable string. Thus, in most cases, the member
    
  225.   value will be a ``(value, label)`` two-tuple. See below for :ref:`an example
    
  226.   of subclassing choices <field-choices-enum-subclassing>` using a more complex
    
  227.   data type. If a tuple is not provided, or the last item is not a (lazy)
    
  228.   string, the ``label`` is :ref:`automatically generated
    
  229.   <field-choices-enum-auto-label>` from the member name.
    
  230. * A ``.label`` property is added on values, to return the human-readable name.
    
  231. * A number of custom properties are added to the enumeration classes --
    
  232.   ``.choices``, ``.labels``, ``.values``, and ``.names`` -- to make it easier
    
  233.   to access lists of those separate parts of the enumeration. Use ``.choices``
    
  234.   as a suitable value to pass to :attr:`~Field.choices` in a field definition.
    
  235. 
    
  236.   .. warning::
    
  237. 
    
  238.     These property names cannot be used as member names as they would conflict.
    
  239. 
    
  240. * The use of :func:`enum.unique()` is enforced to ensure that values cannot be
    
  241.   defined multiple times. This is unlikely to be expected in choices for a
    
  242.   field.
    
  243. 
    
  244. Note that using ``YearInSchool.SENIOR``, ``YearInSchool['SENIOR']``, or
    
  245. ``YearInSchool('SR')`` to access or lookup enum members work as expected, as do
    
  246. the ``.name`` and ``.value`` properties on the members.
    
  247. 
    
  248. .. _field-choices-enum-auto-label:
    
  249. 
    
  250. If you don't need to have the human-readable names translated, you can have
    
  251. them inferred from the member name (replacing underscores with spaces and using
    
  252. title-case)::
    
  253. 
    
  254.     >>> class Vehicle(models.TextChoices):
    
  255.     ...     CAR = 'C'
    
  256.     ...     TRUCK = 'T'
    
  257.     ...     JET_SKI = 'J'
    
  258.     ...
    
  259.     >>> Vehicle.JET_SKI.label
    
  260.     'Jet Ski'
    
  261. 
    
  262. Since the case where the enum values need to be integers is extremely common,
    
  263. Django provides an ``IntegerChoices`` class. For example::
    
  264. 
    
  265.     class Card(models.Model):
    
  266. 
    
  267.         class Suit(models.IntegerChoices):
    
  268.             DIAMOND = 1
    
  269.             SPADE = 2
    
  270.             HEART = 3
    
  271.             CLUB = 4
    
  272. 
    
  273.         suit = models.IntegerField(choices=Suit.choices)
    
  274. 
    
  275. It is also possible to make use of the `Enum Functional API
    
  276. <https://docs.python.org/3/library/enum.html#functional-api>`_ with the caveat
    
  277. that labels are automatically generated as highlighted above::
    
  278. 
    
  279.     >>> MedalType = models.TextChoices('MedalType', 'GOLD SILVER BRONZE')
    
  280.     >>> MedalType.choices
    
  281.     [('GOLD', 'Gold'), ('SILVER', 'Silver'), ('BRONZE', 'Bronze')]
    
  282.     >>> Place = models.IntegerChoices('Place', 'FIRST SECOND THIRD')
    
  283.     >>> Place.choices
    
  284.     [(1, 'First'), (2, 'Second'), (3, 'Third')]
    
  285. 
    
  286. .. _field-choices-enum-subclassing:
    
  287. 
    
  288. If you require support for a concrete data type other than ``int`` or ``str``,
    
  289. you can subclass ``Choices`` and the required concrete data type, e.g.
    
  290. :class:`~datetime.date` for use with :class:`~django.db.models.DateField`::
    
  291. 
    
  292.     class MoonLandings(datetime.date, models.Choices):
    
  293.         APOLLO_11 = 1969, 7, 20, 'Apollo 11 (Eagle)'
    
  294.         APOLLO_12 = 1969, 11, 19, 'Apollo 12 (Intrepid)'
    
  295.         APOLLO_14 = 1971, 2, 5, 'Apollo 14 (Antares)'
    
  296.         APOLLO_15 = 1971, 7, 30, 'Apollo 15 (Falcon)'
    
  297.         APOLLO_16 = 1972, 4, 21, 'Apollo 16 (Orion)'
    
  298.         APOLLO_17 = 1972, 12, 11, 'Apollo 17 (Challenger)'
    
  299. 
    
  300. There are some additional caveats to be aware of:
    
  301. 
    
  302. - Enumeration types do not support :ref:`named groups
    
  303.   <field-choices-named-groups>`.
    
  304. - Because an enumeration with a concrete data type requires all values to match
    
  305.   the type, overriding the :ref:`blank label <field-choices-blank-label>`
    
  306.   cannot be achieved by creating a member with a value of ``None``. Instead,
    
  307.   set the ``__empty__`` attribute on the class::
    
  308. 
    
  309.     class Answer(models.IntegerChoices):
    
  310.         NO = 0, _('No')
    
  311.         YES = 1, _('Yes')
    
  312. 
    
  313.         __empty__ = _('(Unknown)')
    
  314. 
    
  315. ``db_column``
    
  316. -------------
    
  317. 
    
  318. .. attribute:: Field.db_column
    
  319. 
    
  320. The name of the database column to use for this field. If this isn't given,
    
  321. Django will use the field's name.
    
  322. 
    
  323. If your database column name is an SQL reserved word, or contains
    
  324. characters that aren't allowed in Python variable names -- notably, the
    
  325. hyphen -- that's OK. Django quotes column and table names behind the
    
  326. scenes.
    
  327. 
    
  328. ``db_index``
    
  329. ------------
    
  330. 
    
  331. .. attribute:: Field.db_index
    
  332. 
    
  333. If ``True``, a database index will be created for this field.
    
  334. 
    
  335. ``db_tablespace``
    
  336. -----------------
    
  337. 
    
  338. .. attribute:: Field.db_tablespace
    
  339. 
    
  340. The name of the :doc:`database tablespace </topics/db/tablespaces>` to use for
    
  341. this field's index, if this field is indexed. The default is the project's
    
  342. :setting:`DEFAULT_INDEX_TABLESPACE` setting, if set, or the
    
  343. :attr:`~Options.db_tablespace` of the model, if any. If the backend doesn't
    
  344. support tablespaces for indexes, this option is ignored.
    
  345. 
    
  346. ``default``
    
  347. -----------
    
  348. 
    
  349. .. attribute:: Field.default
    
  350. 
    
  351. The default value for the field. This can be a value or a callable object. If
    
  352. callable it will be called every time a new object is created.
    
  353. 
    
  354. The default can't be a mutable object (model instance, ``list``, ``set``, etc.),
    
  355. as a reference to the same instance of that object would be used as the default
    
  356. value in all new model instances. Instead, wrap the desired default in a
    
  357. callable. For example, if you want to specify a default ``dict`` for
    
  358. :class:`~django.db.models.JSONField`, use a function::
    
  359. 
    
  360.     def contact_default():
    
  361.         return {"email": "[email protected]"}
    
  362. 
    
  363.     contact_info = JSONField("ContactInfo", default=contact_default)
    
  364. 
    
  365. ``lambda``\s can't be used for field options like ``default`` because they
    
  366. can't be :ref:`serialized by migrations <migration-serializing>`. See that
    
  367. documentation for other caveats.
    
  368. 
    
  369. For fields like :class:`ForeignKey` that map to model instances, defaults
    
  370. should be the value of the field they reference (``pk`` unless
    
  371. :attr:`~ForeignKey.to_field` is set) instead of model instances.
    
  372. 
    
  373. The default value is used when new model instances are created and a value
    
  374. isn't provided for the field. When the field is a primary key, the default is
    
  375. also used when the field is set to ``None``.
    
  376. 
    
  377. ``editable``
    
  378. ------------
    
  379. 
    
  380. .. attribute:: Field.editable
    
  381. 
    
  382. If ``False``, the field will not be displayed in the admin or any other
    
  383. :class:`~django.forms.ModelForm`. They are also skipped during :ref:`model
    
  384. validation <validating-objects>`. Default is ``True``.
    
  385. 
    
  386. ``error_messages``
    
  387. ------------------
    
  388. 
    
  389. .. attribute:: Field.error_messages
    
  390. 
    
  391. The ``error_messages`` argument lets you override the default messages that the
    
  392. field will raise. Pass in a dictionary with keys matching the error messages you
    
  393. want to override.
    
  394. 
    
  395. Error message keys include ``null``, ``blank``, ``invalid``, ``invalid_choice``,
    
  396. ``unique``, and ``unique_for_date``. Additional error message keys are
    
  397. specified for each field in the `Field types`_ section below.
    
  398. 
    
  399. These error messages often don't propagate to forms. See
    
  400. :ref:`considerations-regarding-model-errormessages`.
    
  401. 
    
  402. ``help_text``
    
  403. -------------
    
  404. 
    
  405. .. attribute:: Field.help_text
    
  406. 
    
  407. Extra "help" text to be displayed with the form widget. It's useful for
    
  408. documentation even if your field isn't used on a form.
    
  409. 
    
  410. Note that this value is *not* HTML-escaped in automatically-generated
    
  411. forms. This lets you include HTML in :attr:`~Field.help_text` if you so
    
  412. desire. For example::
    
  413. 
    
  414.     help_text="Please use the following format: <em>YYYY-MM-DD</em>."
    
  415. 
    
  416. Alternatively you can use plain text and
    
  417. :func:`django.utils.html.escape` to escape any HTML special characters. Ensure
    
  418. that you escape any help text that may come from untrusted users to avoid a
    
  419. cross-site scripting attack.
    
  420. 
    
  421. ``primary_key``
    
  422. ---------------
    
  423. 
    
  424. .. attribute:: Field.primary_key
    
  425. 
    
  426. If ``True``, this field is the primary key for the model.
    
  427. 
    
  428. If you don't specify ``primary_key=True`` for any field in your model, Django
    
  429. will automatically add a field to hold the primary key, so you don't need to
    
  430. set ``primary_key=True`` on any of your fields unless you want to override the
    
  431. default primary-key behavior. The type of auto-created primary key fields can
    
  432. be specified per app in :attr:`AppConfig.default_auto_field
    
  433. <django.apps.AppConfig.default_auto_field>` or globally in the
    
  434. :setting:`DEFAULT_AUTO_FIELD` setting. For more, see
    
  435. :ref:`automatic-primary-key-fields`.
    
  436. 
    
  437. ``primary_key=True`` implies :attr:`null=False <Field.null>` and
    
  438. :attr:`unique=True <Field.unique>`. Only one primary key is allowed on an
    
  439. object.
    
  440. 
    
  441. The primary key field is read-only. If you change the value of the primary
    
  442. key on an existing object and then save it, a new object will be created
    
  443. alongside the old one.
    
  444. 
    
  445. The primary key field is set to ``None`` when
    
  446. :meth:`deleting <django.db.models.Model.delete>` an object.
    
  447. 
    
  448. ``unique``
    
  449. ----------
    
  450. 
    
  451. .. attribute:: Field.unique
    
  452. 
    
  453. If ``True``, this field must be unique throughout the table.
    
  454. 
    
  455. This is enforced at the database level and by model validation. If
    
  456. you try to save a model with a duplicate value in a :attr:`~Field.unique`
    
  457. field, a :exc:`django.db.IntegrityError` will be raised by the model's
    
  458. :meth:`~django.db.models.Model.save` method.
    
  459. 
    
  460. This option is valid on all field types except :class:`ManyToManyField` and
    
  461. :class:`OneToOneField`.
    
  462. 
    
  463. Note that when ``unique`` is ``True``, you don't need to specify
    
  464. :attr:`~Field.db_index`, because ``unique`` implies the creation of an index.
    
  465. 
    
  466. ``unique_for_date``
    
  467. -------------------
    
  468. 
    
  469. .. attribute:: Field.unique_for_date
    
  470. 
    
  471. Set this to the name of a :class:`DateField` or :class:`DateTimeField` to
    
  472. require that this field be unique for the value of the date field.
    
  473. 
    
  474. For example, if you have a field ``title`` that has
    
  475. ``unique_for_date="pub_date"``, then Django wouldn't allow the entry of two
    
  476. records with the same ``title`` and ``pub_date``.
    
  477. 
    
  478. Note that if you set this to point to a :class:`DateTimeField`, only the date
    
  479. portion of the field will be considered. Besides, when :setting:`USE_TZ` is
    
  480. ``True``, the check will be performed in the :ref:`current time zone
    
  481. <default-current-time-zone>` at the time the object gets saved.
    
  482. 
    
  483. This is enforced by :meth:`Model.validate_unique()` during model validation
    
  484. but not at the database level. If any :attr:`~Field.unique_for_date` constraint
    
  485. involves fields that are not part of a :class:`~django.forms.ModelForm` (for
    
  486. example, if one of the fields is listed in ``exclude`` or has
    
  487. :attr:`editable=False<Field.editable>`), :meth:`Model.validate_unique()` will
    
  488. skip validation for that particular constraint.
    
  489. 
    
  490. ``unique_for_month``
    
  491. --------------------
    
  492. 
    
  493. .. attribute:: Field.unique_for_month
    
  494. 
    
  495. Like :attr:`~Field.unique_for_date`, but requires the field to be unique with
    
  496. respect to the month.
    
  497. 
    
  498. ``unique_for_year``
    
  499. -------------------
    
  500. 
    
  501. .. attribute:: Field.unique_for_year
    
  502. 
    
  503. Like :attr:`~Field.unique_for_date` and :attr:`~Field.unique_for_month`.
    
  504. 
    
  505. ``verbose_name``
    
  506. ----------------
    
  507. 
    
  508. .. attribute:: Field.verbose_name
    
  509. 
    
  510. A human-readable name for the field. If the verbose name isn't given, Django
    
  511. will automatically create it using the field's attribute name, converting
    
  512. underscores to spaces. See :ref:`Verbose field names <verbose-field-names>`.
    
  513. 
    
  514. ``validators``
    
  515. --------------
    
  516. 
    
  517. .. attribute:: Field.validators
    
  518. 
    
  519. A list of validators to run for this field. See the :doc:`validators
    
  520. documentation </ref/validators>` for more information.
    
  521. 
    
  522. .. _model-field-types:
    
  523. 
    
  524. Field types
    
  525. ===========
    
  526. 
    
  527. .. currentmodule:: django.db.models
    
  528. 
    
  529. ``AutoField``
    
  530. -------------
    
  531. 
    
  532. .. class:: AutoField(**options)
    
  533. 
    
  534. An :class:`IntegerField` that automatically increments
    
  535. according to available IDs. You usually won't need to use this directly; a
    
  536. primary key field will automatically be added to your model if you don't specify
    
  537. otherwise. See :ref:`automatic-primary-key-fields`.
    
  538. 
    
  539. ``BigAutoField``
    
  540. ----------------
    
  541. 
    
  542. .. class:: BigAutoField(**options)
    
  543. 
    
  544. A 64-bit integer, much like an :class:`AutoField` except that it is
    
  545. guaranteed to fit numbers from ``1`` to ``9223372036854775807``.
    
  546. 
    
  547. ``BigIntegerField``
    
  548. -------------------
    
  549. 
    
  550. .. class:: BigIntegerField(**options)
    
  551. 
    
  552. A 64-bit integer, much like an :class:`IntegerField` except that it is
    
  553. guaranteed to fit numbers from ``-9223372036854775808`` to
    
  554. ``9223372036854775807``. The default form widget for this field is a
    
  555. :class:`~django.forms.NumberInput`.
    
  556. 
    
  557. ``BinaryField``
    
  558. ---------------
    
  559. 
    
  560. .. class:: BinaryField(max_length=None, **options)
    
  561. 
    
  562. A field to store raw binary data. It can be assigned :class:`bytes`,
    
  563. :class:`bytearray`, or :class:`memoryview`.
    
  564. 
    
  565. By default, ``BinaryField`` sets :attr:`~Field.editable` to ``False``, in which
    
  566. case it can't be included in a :class:`~django.forms.ModelForm`.
    
  567. 
    
  568. .. attribute:: BinaryField.max_length
    
  569. 
    
  570.     Optional. The maximum length (in bytes) of the field. The maximum length is
    
  571.     enforced in Django's validation using
    
  572.     :class:`~django.core.validators.MaxLengthValidator`.
    
  573. 
    
  574. .. admonition:: Abusing ``BinaryField``
    
  575. 
    
  576.     Although you might think about storing files in the database, consider that
    
  577.     it is bad design in 99% of the cases. This field is *not* a replacement for
    
  578.     proper :doc:`static files </howto/static-files/index>` handling.
    
  579. 
    
  580. ``BooleanField``
    
  581. ----------------
    
  582. 
    
  583. .. class:: BooleanField(**options)
    
  584. 
    
  585. A true/false field.
    
  586. 
    
  587. The default form widget for this field is :class:`~django.forms.CheckboxInput`,
    
  588. or :class:`~django.forms.NullBooleanSelect` if :attr:`null=True <Field.null>`.
    
  589. 
    
  590. The default value of ``BooleanField`` is ``None`` when :attr:`Field.default`
    
  591. isn't defined.
    
  592. 
    
  593. ``CharField``
    
  594. -------------
    
  595. 
    
  596. .. class:: CharField(max_length=None, **options)
    
  597. 
    
  598. A string field, for small- to large-sized strings.
    
  599. 
    
  600. For large amounts of text, use :class:`~django.db.models.TextField`.
    
  601. 
    
  602. The default form widget for this field is a :class:`~django.forms.TextInput`.
    
  603. 
    
  604. :class:`CharField` has the following extra arguments:
    
  605. 
    
  606. .. attribute:: CharField.max_length
    
  607. 
    
  608.     Required. The maximum length (in characters) of the field. The max_length
    
  609.     is enforced at the database level and in Django's validation using
    
  610.     :class:`~django.core.validators.MaxLengthValidator`.
    
  611. 
    
  612.     .. note::
    
  613. 
    
  614.         If you are writing an application that must be portable to multiple
    
  615.         database backends, you should be aware that there are restrictions on
    
  616.         ``max_length`` for some backends. Refer to the :doc:`database backend
    
  617.         notes </ref/databases>` for details.
    
  618. 
    
  619. .. attribute:: CharField.db_collation
    
  620. 
    
  621.     Optional. The database collation name of the field.
    
  622. 
    
  623.     .. note::
    
  624. 
    
  625.         Collation names are not standardized. As such, this will not be
    
  626.         portable across multiple database backends.
    
  627. 
    
  628.     .. admonition:: Oracle
    
  629. 
    
  630.         Oracle supports collations only when the ``MAX_STRING_SIZE`` database
    
  631.         initialization parameter is set to ``EXTENDED``.
    
  632. 
    
  633. ``DateField``
    
  634. -------------
    
  635. 
    
  636. .. class:: DateField(auto_now=False, auto_now_add=False, **options)
    
  637. 
    
  638. A date, represented in Python by a ``datetime.date`` instance. Has a few extra,
    
  639. optional arguments:
    
  640. 
    
  641. .. attribute:: DateField.auto_now
    
  642. 
    
  643.     Automatically set the field to now every time the object is saved. Useful
    
  644.     for "last-modified" timestamps. Note that the current date is *always*
    
  645.     used; it's not just a default value that you can override.
    
  646. 
    
  647.     The field is only automatically updated when calling :meth:`Model.save()
    
  648.     <django.db.models.Model.save>`. The field isn't updated when making updates
    
  649.     to other fields in other ways such as :meth:`QuerySet.update()
    
  650.     <django.db.models.query.QuerySet.update>`, though you can specify a custom
    
  651.     value for the field in an update like that.
    
  652. 
    
  653. .. attribute:: DateField.auto_now_add
    
  654. 
    
  655.     Automatically set the field to now when the object is first created. Useful
    
  656.     for creation of timestamps. Note that the current date is *always* used;
    
  657.     it's not just a default value that you can override. So even if you
    
  658.     set a value for this field when creating the object, it will be ignored.
    
  659.     If you want to be able to modify this field, set the following instead of
    
  660.     ``auto_now_add=True``:
    
  661. 
    
  662.     * For :class:`DateField`: ``default=date.today`` - from
    
  663.       :meth:`datetime.date.today`
    
  664.     * For :class:`DateTimeField`: ``default=timezone.now`` - from
    
  665.       :func:`django.utils.timezone.now`
    
  666. 
    
  667. The default form widget for this field is a
    
  668. :class:`~django.forms.DateInput`. The admin adds a JavaScript calendar,
    
  669. and a shortcut for "Today". Includes an additional ``invalid_date`` error
    
  670. message key.
    
  671. 
    
  672. The options ``auto_now_add``, ``auto_now``, and ``default`` are mutually exclusive.
    
  673. Any combination of these options will result in an error.
    
  674. 
    
  675. .. note::
    
  676.     As currently implemented, setting ``auto_now`` or ``auto_now_add`` to
    
  677.     ``True`` will cause the field to have ``editable=False`` and ``blank=True``
    
  678.     set.
    
  679. 
    
  680. .. note::
    
  681.     The ``auto_now`` and ``auto_now_add`` options will always use the date in
    
  682.     the :ref:`default timezone <default-current-time-zone>` at the moment of
    
  683.     creation or update. If you need something different, you may want to
    
  684.     consider using your own callable default or overriding ``save()`` instead
    
  685.     of using ``auto_now`` or ``auto_now_add``; or using a ``DateTimeField``
    
  686.     instead of a ``DateField`` and deciding how to handle the conversion from
    
  687.     datetime to date at display time.
    
  688. 
    
  689. ``DateTimeField``
    
  690. -----------------
    
  691. 
    
  692. .. class:: DateTimeField(auto_now=False, auto_now_add=False, **options)
    
  693. 
    
  694. A date and time, represented in Python by a ``datetime.datetime`` instance.
    
  695. Takes the same extra arguments as :class:`DateField`.
    
  696. 
    
  697. The default form widget for this field is a single
    
  698. :class:`~django.forms.DateTimeInput`. The admin uses two separate
    
  699. :class:`~django.forms.TextInput` widgets with JavaScript shortcuts.
    
  700. 
    
  701. ``DecimalField``
    
  702. ----------------
    
  703. 
    
  704. .. class:: DecimalField(max_digits=None, decimal_places=None, **options)
    
  705. 
    
  706. A fixed-precision decimal number, represented in Python by a
    
  707. :class:`~decimal.Decimal` instance. It validates the input using
    
  708. :class:`~django.core.validators.DecimalValidator`.
    
  709. 
    
  710. Has the following **required** arguments:
    
  711. 
    
  712. .. attribute:: DecimalField.max_digits
    
  713. 
    
  714.     The maximum number of digits allowed in the number. Note that this number
    
  715.     must be greater than or equal to ``decimal_places``.
    
  716. 
    
  717. .. attribute:: DecimalField.decimal_places
    
  718. 
    
  719.     The number of decimal places to store with the number.
    
  720. 
    
  721. For example, to store numbers up to ``999.99`` with a resolution of 2 decimal
    
  722. places, you'd use::
    
  723. 
    
  724.     models.DecimalField(..., max_digits=5, decimal_places=2)
    
  725. 
    
  726. And to store numbers up to approximately one billion with a resolution of 10
    
  727. decimal places::
    
  728. 
    
  729.     models.DecimalField(..., max_digits=19, decimal_places=10)
    
  730. 
    
  731. The default form widget for this field is a :class:`~django.forms.NumberInput`
    
  732. when :attr:`~django.forms.Field.localize` is ``False`` or
    
  733. :class:`~django.forms.TextInput` otherwise.
    
  734. 
    
  735. .. note::
    
  736. 
    
  737.     For more information about the differences between the
    
  738.     :class:`FloatField` and :class:`DecimalField` classes, please
    
  739.     see :ref:`FloatField vs. DecimalField <floatfield_vs_decimalfield>`. You
    
  740.     should also be aware of :ref:`SQLite limitations <sqlite-decimal-handling>`
    
  741.     of decimal fields.
    
  742. 
    
  743. ``DurationField``
    
  744. -----------------
    
  745. 
    
  746. .. class:: DurationField(**options)
    
  747. 
    
  748. A field for storing periods of time - modeled in Python by
    
  749. :class:`~python:datetime.timedelta`. When used on PostgreSQL, the data type
    
  750. used is an ``interval`` and on Oracle the data type is ``INTERVAL DAY(9) TO
    
  751. SECOND(6)``. Otherwise a ``bigint`` of microseconds is used.
    
  752. 
    
  753. .. note::
    
  754. 
    
  755.     Arithmetic with ``DurationField`` works in most cases. However on all
    
  756.     databases other than PostgreSQL, comparing the value of a ``DurationField``
    
  757.     to arithmetic on ``DateTimeField`` instances will not work as expected.
    
  758. 
    
  759. ``EmailField``
    
  760. --------------
    
  761. 
    
  762. .. class:: EmailField(max_length=254, **options)
    
  763. 
    
  764. A :class:`CharField` that checks that the value is a valid email address using
    
  765. :class:`~django.core.validators.EmailValidator`.
    
  766. 
    
  767. ``FileField``
    
  768. -------------
    
  769. 
    
  770. .. class:: FileField(upload_to='', storage=None, max_length=100, **options)
    
  771. 
    
  772. A file-upload field.
    
  773. 
    
  774. .. note::
    
  775.     The ``primary_key`` argument isn't supported and will raise an error if
    
  776.     used.
    
  777. 
    
  778. Has the following optional arguments:
    
  779. 
    
  780. .. attribute:: FileField.upload_to
    
  781. 
    
  782.     This attribute provides a way of setting the upload directory and file name,
    
  783.     and can be set in two ways. In both cases, the value is passed to the
    
  784.     :meth:`Storage.save() <django.core.files.storage.Storage.save>` method.
    
  785. 
    
  786.     If you specify a string value or a :class:`~pathlib.Path`, it may contain
    
  787.     :func:`~time.strftime` formatting, which will be replaced by the date/time
    
  788.     of the file upload (so that uploaded files don't fill up the given
    
  789.     directory). For example::
    
  790. 
    
  791.         class MyModel(models.Model):
    
  792.             # file will be uploaded to MEDIA_ROOT/uploads
    
  793.             upload = models.FileField(upload_to='uploads/')
    
  794.             # or...
    
  795.             # file will be saved to MEDIA_ROOT/uploads/2015/01/30
    
  796.             upload = models.FileField(upload_to='uploads/%Y/%m/%d/')
    
  797. 
    
  798.     If you are using the default
    
  799.     :class:`~django.core.files.storage.FileSystemStorage`, the string value
    
  800.     will be appended to your :setting:`MEDIA_ROOT` path to form the location on
    
  801.     the local filesystem where uploaded files will be stored. If you are using
    
  802.     a different storage, check that storage's documentation to see how it
    
  803.     handles ``upload_to``.
    
  804. 
    
  805.     ``upload_to`` may also be a callable, such as a function. This will be
    
  806.     called to obtain the upload path, including the filename. This callable must
    
  807.     accept two arguments and return a Unix-style path (with forward slashes)
    
  808.     to be passed along to the storage system. The two arguments are:
    
  809. 
    
  810.     ======================  ===============================================
    
  811.     Argument                Description
    
  812.     ======================  ===============================================
    
  813.     ``instance``            An instance of the model where the
    
  814.                             ``FileField`` is defined. More specifically,
    
  815.                             this is the particular instance where the
    
  816.                             current file is being attached.
    
  817. 
    
  818.                             In most cases, this object will not have been
    
  819.                             saved to the database yet, so if it uses the
    
  820.                             default ``AutoField``, *it might not yet have a
    
  821.                             value for its primary key field*.
    
  822. 
    
  823.     ``filename``            The filename that was originally given to the
    
  824.                             file. This may or may not be taken into account
    
  825.                             when determining the final destination path.
    
  826.     ======================  ===============================================
    
  827. 
    
  828.     For example::
    
  829. 
    
  830.         def user_directory_path(instance, filename):
    
  831.             # file will be uploaded to MEDIA_ROOT/user_<id>/<filename>
    
  832.             return 'user_{0}/{1}'.format(instance.user.id, filename)
    
  833. 
    
  834.         class MyModel(models.Model):
    
  835.             upload = models.FileField(upload_to=user_directory_path)
    
  836. 
    
  837. .. attribute:: FileField.storage
    
  838. 
    
  839.     A storage object, or a callable which returns a storage object. This
    
  840.     handles the storage and retrieval of your files. See :doc:`/topics/files`
    
  841.     for details on how to provide this object.
    
  842. 
    
  843. The default form widget for this field is a
    
  844. :class:`~django.forms.ClearableFileInput`.
    
  845. 
    
  846. Using a :class:`FileField` or an :class:`ImageField` (see below) in a model
    
  847. takes a few steps:
    
  848. 
    
  849. #. In your settings file, you'll need to define :setting:`MEDIA_ROOT` as the
    
  850.    full path to a directory where you'd like Django to store uploaded files.
    
  851.    (For performance, these files are not stored in the database.) Define
    
  852.    :setting:`MEDIA_URL` as the base public URL of that directory. Make sure
    
  853.    that this directory is writable by the web server's user account.
    
  854. 
    
  855. #. Add the :class:`FileField` or :class:`ImageField` to your model, defining
    
  856.    the :attr:`~FileField.upload_to` option to specify a subdirectory of
    
  857.    :setting:`MEDIA_ROOT` to use for uploaded files.
    
  858. 
    
  859. #. All that will be stored in your database is a path to the file
    
  860.    (relative to :setting:`MEDIA_ROOT`). You'll most likely want to use the
    
  861.    convenience :attr:`~django.db.models.fields.files.FieldFile.url` attribute
    
  862.    provided by Django. For example, if your :class:`ImageField` is called
    
  863.    ``mug_shot``, you can get the absolute path to your image in a template with
    
  864.    ``{{ object.mug_shot.url }}``.
    
  865. 
    
  866. For example, say your :setting:`MEDIA_ROOT` is set to ``'/home/media'``, and
    
  867. :attr:`~FileField.upload_to` is set to ``'photos/%Y/%m/%d'``. The ``'%Y/%m/%d'``
    
  868. part of :attr:`~FileField.upload_to` is :func:`~time.strftime` formatting;
    
  869. ``'%Y'`` is the four-digit year, ``'%m'`` is the two-digit month and ``'%d'`` is
    
  870. the two-digit day. If you upload a file on Jan. 15, 2007, it will be saved in
    
  871. the directory ``/home/media/photos/2007/01/15``.
    
  872. 
    
  873. If you wanted to retrieve the uploaded file's on-disk filename, or the file's
    
  874. size, you could use the :attr:`~django.core.files.File.name` and
    
  875. :attr:`~django.core.files.File.size` attributes respectively; for more
    
  876. information on the available attributes and methods, see the
    
  877. :class:`~django.core.files.File` class reference and the :doc:`/topics/files`
    
  878. topic guide.
    
  879. 
    
  880. .. note::
    
  881.     The file is saved as part of saving the model in the database, so the actual
    
  882.     file name used on disk cannot be relied on until after the model has been
    
  883.     saved.
    
  884. 
    
  885. The uploaded file's relative URL can be obtained using the
    
  886. :attr:`~django.db.models.fields.files.FieldFile.url` attribute. Internally,
    
  887. this calls the :meth:`~django.core.files.storage.Storage.url` method of the
    
  888. underlying :class:`~django.core.files.storage.Storage` class.
    
  889. 
    
  890. .. _file-upload-security:
    
  891. 
    
  892. Note that whenever you deal with uploaded files, you should pay close attention
    
  893. to where you're uploading them and what type of files they are, to avoid
    
  894. security holes. *Validate all uploaded files* so that you're sure the files are
    
  895. what you think they are. For example, if you blindly let somebody upload files,
    
  896. without validation, to a directory that's within your web server's document
    
  897. root, then somebody could upload a CGI or PHP script and execute that script by
    
  898. visiting its URL on your site. Don't allow that.
    
  899. 
    
  900. Also note that even an uploaded HTML file, since it can be executed by the
    
  901. browser (though not by the server), can pose security threats that are
    
  902. equivalent to XSS or CSRF attacks.
    
  903. 
    
  904. :class:`FileField` instances are created in your database as ``varchar``
    
  905. columns with a default max length of 100 characters. As with other fields, you
    
  906. can change the maximum length using the :attr:`~CharField.max_length` argument.
    
  907. 
    
  908. ``FileField`` and ``FieldFile``
    
  909. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
  910. 
    
  911. .. currentmodule:: django.db.models.fields.files
    
  912. 
    
  913. .. class:: FieldFile
    
  914. 
    
  915. When you access a :class:`~django.db.models.FileField` on a model, you are
    
  916. given an instance of :class:`FieldFile` as a proxy for accessing the underlying
    
  917. file.
    
  918. 
    
  919. The API of :class:`FieldFile` mirrors that of :class:`~django.core.files.File`,
    
  920. with one key difference: *The object wrapped by the class is not necessarily a
    
  921. wrapper around Python's built-in file object.* Instead, it is a wrapper around
    
  922. the result of the :attr:`Storage.open()<django.core.files.storage.Storage.open>`
    
  923. method, which may be a :class:`~django.core.files.File` object, or it may be a
    
  924. custom storage's implementation of the :class:`~django.core.files.File` API.
    
  925. 
    
  926. In addition to the API inherited from :class:`~django.core.files.File` such as
    
  927. ``read()`` and ``write()``, :class:`FieldFile` includes several methods that
    
  928. can be used to interact with the underlying file:
    
  929. 
    
  930. .. warning::
    
  931. 
    
  932.     Two methods of this class, :meth:`~FieldFile.save` and
    
  933.     :meth:`~FieldFile.delete`, default to saving the model object of the
    
  934.     associated ``FieldFile`` in the database.
    
  935. 
    
  936. .. attribute:: FieldFile.name
    
  937. 
    
  938. The name of the file including the relative path from the root of the
    
  939. :class:`~django.core.files.storage.Storage` of the associated
    
  940. :class:`~django.db.models.FileField`.
    
  941. 
    
  942. .. attribute:: FieldFile.path
    
  943. 
    
  944. A read-only property to access the file's local filesystem path by calling the
    
  945. :meth:`~django.core.files.storage.Storage.path` method of the underlying
    
  946. :class:`~django.core.files.storage.Storage` class.
    
  947. 
    
  948. .. attribute:: FieldFile.size
    
  949. 
    
  950. The result of the underlying :attr:`Storage.size()
    
  951. <django.core.files.storage.Storage.size>` method.
    
  952. 
    
  953. .. attribute:: FieldFile.url
    
  954. 
    
  955. A read-only property to access the file's relative URL by calling the
    
  956. :meth:`~django.core.files.storage.Storage.url` method of the underlying
    
  957. :class:`~django.core.files.storage.Storage` class.
    
  958. 
    
  959. .. method:: FieldFile.open(mode='rb')
    
  960. 
    
  961. Opens or reopens the file associated with this instance in the specified
    
  962. ``mode``. Unlike the standard Python ``open()`` method, it doesn't return a
    
  963. file descriptor.
    
  964. 
    
  965. Since the underlying file is opened implicitly when accessing it, it may be
    
  966. unnecessary to call this method except to reset the pointer to the underlying
    
  967. file or to change the ``mode``.
    
  968. 
    
  969. .. method:: FieldFile.close()
    
  970. 
    
  971. Behaves like the standard Python ``file.close()`` method and closes the file
    
  972. associated with this instance.
    
  973. 
    
  974. .. method:: FieldFile.save(name, content, save=True)
    
  975. 
    
  976. This method takes a filename and file contents and passes them to the storage
    
  977. class for the field, then associates the stored file with the model field.
    
  978. If you want to manually associate file data with
    
  979. :class:`~django.db.models.FileField` instances on your model, the ``save()``
    
  980. method is used to persist that file data.
    
  981. 
    
  982. Takes two required arguments: ``name`` which is the name of the file, and
    
  983. ``content`` which is an object containing the file's contents.  The
    
  984. optional ``save`` argument controls whether or not the model instance is
    
  985. saved after the file associated with this field has been altered. Defaults to
    
  986. ``True``.
    
  987. 
    
  988. Note that the ``content`` argument should be an instance of
    
  989. :class:`django.core.files.File`, not Python's built-in file object.
    
  990. You can construct a :class:`~django.core.files.File` from an existing
    
  991. Python file object like this::
    
  992. 
    
  993.     from django.core.files import File
    
  994.     # Open an existing file using Python's built-in open()
    
  995.     f = open('/path/to/hello.world')
    
  996.     myfile = File(f)
    
  997. 
    
  998. Or you can construct one from a Python string like this::
    
  999. 
    
  1000.     from django.core.files.base import ContentFile
    
  1001.     myfile = ContentFile("hello world")
    
  1002. 
    
  1003. For more information, see :doc:`/topics/files`.
    
  1004. 
    
  1005. .. method:: FieldFile.delete(save=True)
    
  1006. 
    
  1007. Deletes the file associated with this instance and clears all attributes on
    
  1008. the field. Note: This method will close the file if it happens to be open when
    
  1009. ``delete()`` is called.
    
  1010. 
    
  1011. The optional ``save`` argument controls whether or not the model instance is
    
  1012. saved after the file associated with this field has been deleted. Defaults to
    
  1013. ``True``.
    
  1014. 
    
  1015. Note that when a model is deleted, related files are not deleted. If you need
    
  1016. to cleanup orphaned files, you'll need to handle it yourself (for instance,
    
  1017. with a custom management command that can be run manually or scheduled to run
    
  1018. periodically via e.g. cron).
    
  1019. 
    
  1020. .. currentmodule:: django.db.models
    
  1021. 
    
  1022. ``FilePathField``
    
  1023. -----------------
    
  1024. 
    
  1025. .. class:: FilePathField(path='', match=None, recursive=False, allow_files=True, allow_folders=False, max_length=100, **options)
    
  1026. 
    
  1027. A :class:`CharField` whose choices are limited to the filenames in a certain
    
  1028. directory on the filesystem. Has some special arguments, of which the first is
    
  1029. **required**:
    
  1030. 
    
  1031. .. attribute:: FilePathField.path
    
  1032. 
    
  1033.     Required. The absolute filesystem path to a directory from which this
    
  1034.     :class:`FilePathField` should get its choices. Example: ``"/home/images"``.
    
  1035. 
    
  1036.     ``path`` may also be a callable, such as a function to dynamically set the
    
  1037.     path at runtime. Example::
    
  1038. 
    
  1039.         import os
    
  1040.         from django.conf import settings
    
  1041.         from django.db import models
    
  1042. 
    
  1043.         def images_path():
    
  1044.             return os.path.join(settings.LOCAL_FILE_DIR, 'images')
    
  1045. 
    
  1046.         class MyModel(models.Model):
    
  1047.             file = models.FilePathField(path=images_path)
    
  1048. 
    
  1049. .. attribute:: FilePathField.match
    
  1050. 
    
  1051.     Optional. A regular expression, as a string, that :class:`FilePathField`
    
  1052.     will use to filter filenames. Note that the regex will be applied to the
    
  1053.     base filename, not the full path. Example: ``"foo.*\.txt$"``, which will
    
  1054.     match a file called ``foo23.txt`` but not ``bar.txt`` or ``foo23.png``.
    
  1055. 
    
  1056. .. attribute:: FilePathField.recursive
    
  1057. 
    
  1058.     Optional. Either ``True`` or ``False``. Default is ``False``. Specifies
    
  1059.     whether all subdirectories of :attr:`~FilePathField.path` should be included
    
  1060. 
    
  1061. .. attribute:: FilePathField.allow_files
    
  1062. 
    
  1063.     Optional.  Either ``True`` or ``False``.  Default is ``True``.  Specifies
    
  1064.     whether files in the specified location should be included.  Either this or
    
  1065.     :attr:`~FilePathField.allow_folders` must be ``True``.
    
  1066. 
    
  1067. .. attribute:: FilePathField.allow_folders
    
  1068. 
    
  1069.     Optional.  Either ``True`` or ``False``.  Default is ``False``.  Specifies
    
  1070.     whether folders in the specified location should be included.  Either this
    
  1071.     or :attr:`~FilePathField.allow_files` must be ``True``.
    
  1072. 
    
  1073. The one potential gotcha is that :attr:`~FilePathField.match` applies to the
    
  1074. base filename, not the full path. So, this example::
    
  1075. 
    
  1076.     FilePathField(path="/home/images", match="foo.*", recursive=True)
    
  1077. 
    
  1078. ...will match ``/home/images/foo.png`` but not ``/home/images/foo/bar.png``
    
  1079. because the :attr:`~FilePathField.match` applies to the base filename
    
  1080. (``foo.png`` and ``bar.png``).
    
  1081. 
    
  1082. :class:`FilePathField` instances are created in your database as ``varchar``
    
  1083. columns with a default max length of 100 characters. As with other fields, you
    
  1084. can change the maximum length using the :attr:`~CharField.max_length` argument.
    
  1085. 
    
  1086. ``FloatField``
    
  1087. --------------
    
  1088. 
    
  1089. .. class:: FloatField(**options)
    
  1090. 
    
  1091. A floating-point number represented in Python by a ``float`` instance.
    
  1092. 
    
  1093. The default form widget for this field is a :class:`~django.forms.NumberInput`
    
  1094. when :attr:`~django.forms.Field.localize` is ``False`` or
    
  1095. :class:`~django.forms.TextInput` otherwise.
    
  1096. 
    
  1097. .. _floatfield_vs_decimalfield:
    
  1098. 
    
  1099. .. admonition:: ``FloatField`` vs. ``DecimalField``
    
  1100. 
    
  1101.     The :class:`FloatField` class is sometimes mixed up with the
    
  1102.     :class:`DecimalField` class. Although they both represent real numbers, they
    
  1103.     represent those numbers differently. ``FloatField`` uses Python's ``float``
    
  1104.     type internally, while ``DecimalField`` uses Python's ``Decimal`` type. For
    
  1105.     information on the difference between the two, see Python's documentation
    
  1106.     for the :mod:`decimal` module.
    
  1107. 
    
  1108. ``GenericIPAddressField``
    
  1109. -------------------------
    
  1110. 
    
  1111. .. class:: GenericIPAddressField(protocol='both', unpack_ipv4=False, **options)
    
  1112. 
    
  1113. An IPv4 or IPv6 address, in string format (e.g. ``192.0.2.30`` or
    
  1114. ``2a02:42fe::4``). The default form widget for this field is a
    
  1115. :class:`~django.forms.TextInput`.
    
  1116. 
    
  1117. The IPv6 address normalization follows :rfc:`4291#section-2.2` section 2.2,
    
  1118. including using the IPv4 format suggested in paragraph 3 of that section, like
    
  1119. ``::ffff:192.0.2.0``. For example, ``2001:0::0:01`` would be normalized to
    
  1120. ``2001::1``, and ``::ffff:0a0a:0a0a`` to ``::ffff:10.10.10.10``. All characters
    
  1121. are converted to lowercase.
    
  1122. 
    
  1123. .. attribute:: GenericIPAddressField.protocol
    
  1124. 
    
  1125.     Limits valid inputs to the specified protocol.
    
  1126.     Accepted values are ``'both'`` (default), ``'IPv4'``
    
  1127.     or ``'IPv6'``. Matching is case insensitive.
    
  1128. 
    
  1129. .. attribute:: GenericIPAddressField.unpack_ipv4
    
  1130. 
    
  1131.     Unpacks IPv4 mapped addresses like ``::ffff:192.0.2.1``.
    
  1132.     If this option is enabled that address would be unpacked to
    
  1133.     ``192.0.2.1``. Default is disabled. Can only be used
    
  1134.     when ``protocol`` is set to ``'both'``.
    
  1135. 
    
  1136. If you allow for blank values, you have to allow for null values since blank
    
  1137. values are stored as null.
    
  1138. 
    
  1139. ``ImageField``
    
  1140. --------------
    
  1141. 
    
  1142. .. class:: ImageField(upload_to=None, height_field=None, width_field=None, max_length=100, **options)
    
  1143. 
    
  1144. Inherits all attributes and methods from :class:`FileField`, but also
    
  1145. validates that the uploaded object is a valid image.
    
  1146. 
    
  1147. In addition to the special attributes that are available for :class:`FileField`,
    
  1148. an :class:`ImageField` also has ``height`` and ``width`` attributes.
    
  1149. 
    
  1150. To facilitate querying on those attributes, :class:`ImageField` has the
    
  1151. following optional arguments:
    
  1152. 
    
  1153. .. attribute:: ImageField.height_field
    
  1154. 
    
  1155.     Name of a model field which will be auto-populated with the height of the
    
  1156.     image each time the model instance is saved.
    
  1157. 
    
  1158. .. attribute:: ImageField.width_field
    
  1159. 
    
  1160.     Name of a model field which will be auto-populated with the width of the
    
  1161.     image each time the model instance is saved.
    
  1162. 
    
  1163. Requires the `Pillow`_ library.
    
  1164. 
    
  1165. .. _Pillow: https://pillow.readthedocs.io/en/latest/
    
  1166. 
    
  1167. :class:`ImageField` instances are created in your database as ``varchar``
    
  1168. columns with a default max length of 100 characters. As with other fields, you
    
  1169. can change the maximum length using the :attr:`~CharField.max_length` argument.
    
  1170. 
    
  1171. The default form widget for this field is a
    
  1172. :class:`~django.forms.ClearableFileInput`.
    
  1173. 
    
  1174. ``IntegerField``
    
  1175. ----------------
    
  1176. 
    
  1177. .. class:: IntegerField(**options)
    
  1178. 
    
  1179. An integer. Values from ``-2147483648`` to ``2147483647`` are safe in all
    
  1180. databases supported by Django.
    
  1181. 
    
  1182. It uses :class:`~django.core.validators.MinValueValidator` and
    
  1183. :class:`~django.core.validators.MaxValueValidator` to validate the input based
    
  1184. on the values that the default database supports.
    
  1185. 
    
  1186. The default form widget for this field is a :class:`~django.forms.NumberInput`
    
  1187. when :attr:`~django.forms.Field.localize` is ``False`` or
    
  1188. :class:`~django.forms.TextInput` otherwise.
    
  1189. 
    
  1190. ``JSONField``
    
  1191. -------------
    
  1192. 
    
  1193. .. class:: JSONField(encoder=None, decoder=None, **options)
    
  1194. 
    
  1195. A field for storing JSON encoded data. In Python the data is represented in its
    
  1196. Python native format: dictionaries, lists, strings, numbers, booleans and
    
  1197. ``None``.
    
  1198. 
    
  1199. ``JSONField`` is supported on MariaDB, MySQL 5.7.8+, Oracle, PostgreSQL, and
    
  1200. SQLite (with the :ref:`JSON1 extension enabled <sqlite-json1>`).
    
  1201. 
    
  1202. .. attribute:: JSONField.encoder
    
  1203. 
    
  1204.     An optional :py:class:`json.JSONEncoder` subclass to serialize data types
    
  1205.     not supported by the standard JSON serializer (e.g. ``datetime.datetime``
    
  1206.     or :class:`~python:uuid.UUID`). For example, you can use the
    
  1207.     :class:`~django.core.serializers.json.DjangoJSONEncoder` class.
    
  1208. 
    
  1209.     Defaults to ``json.JSONEncoder``.
    
  1210. 
    
  1211. .. attribute:: JSONField.decoder
    
  1212. 
    
  1213.     An optional :py:class:`json.JSONDecoder` subclass to deserialize the value
    
  1214.     retrieved from the database. The value will be in the format chosen by the
    
  1215.     custom encoder (most often a string). Your deserialization may need to
    
  1216.     account for the fact that you can't be certain of the input type. For
    
  1217.     example, you run the risk of returning a ``datetime`` that was actually a
    
  1218.     string that just happened to be in the same format chosen for
    
  1219.     ``datetime``\s.
    
  1220. 
    
  1221.     Defaults to ``json.JSONDecoder``.
    
  1222. 
    
  1223. If you give the field a :attr:`~django.db.models.Field.default`, ensure it's an
    
  1224. immutable object, such as a ``str``, or a callable object that returns a fresh
    
  1225. mutable object each time, such as ``dict`` or a function. Providing a mutable
    
  1226. default object like ``default={}`` or ``default=[]`` shares the one object
    
  1227. between all model instances.
    
  1228. 
    
  1229. To query ``JSONField`` in the database, see :ref:`querying-jsonfield`.
    
  1230. 
    
  1231. .. admonition:: Indexing
    
  1232. 
    
  1233.     :class:`~django.db.models.Index` and :attr:`.Field.db_index` both create a
    
  1234.     B-tree index, which isn't particularly helpful when querying ``JSONField``.
    
  1235.     On PostgreSQL only, you can use
    
  1236.     :class:`~django.contrib.postgres.indexes.GinIndex` that is better suited.
    
  1237. 
    
  1238. .. admonition:: PostgreSQL users
    
  1239. 
    
  1240.     PostgreSQL has two native JSON based data types: ``json`` and ``jsonb``.
    
  1241.     The main difference between them is how they are stored and how they can be
    
  1242.     queried. PostgreSQL's ``json`` field is stored as the original string
    
  1243.     representation of the JSON and must be decoded on the fly when queried
    
  1244.     based on keys. The ``jsonb`` field is stored based on the actual structure
    
  1245.     of the JSON which allows indexing. The trade-off is a small additional cost
    
  1246.     on writing to the ``jsonb`` field. ``JSONField`` uses ``jsonb``.
    
  1247. 
    
  1248. .. admonition:: Oracle users
    
  1249. 
    
  1250.     Oracle Database does not support storing JSON scalar values. Only JSON
    
  1251.     objects and arrays (represented in Python using :py:class:`dict` and
    
  1252.     :py:class:`list`) are supported.
    
  1253. 
    
  1254. ``PositiveBigIntegerField``
    
  1255. ---------------------------
    
  1256. 
    
  1257. .. class:: PositiveBigIntegerField(**options)
    
  1258. 
    
  1259. Like a :class:`PositiveIntegerField`, but only allows values under a certain
    
  1260. (database-dependent) point. Values from ``0`` to ``9223372036854775807`` are
    
  1261. safe in all databases supported by Django.
    
  1262. 
    
  1263. ``PositiveIntegerField``
    
  1264. ------------------------
    
  1265. 
    
  1266. .. class:: PositiveIntegerField(**options)
    
  1267. 
    
  1268. Like an :class:`IntegerField`, but must be either positive or zero (``0``).
    
  1269. Values from ``0`` to ``2147483647`` are safe in all databases supported by
    
  1270. Django. The value ``0`` is accepted for backward compatibility reasons.
    
  1271. 
    
  1272. ``PositiveSmallIntegerField``
    
  1273. -----------------------------
    
  1274. 
    
  1275. .. class:: PositiveSmallIntegerField(**options)
    
  1276. 
    
  1277. Like a :class:`PositiveIntegerField`, but only allows values under a certain
    
  1278. (database-dependent) point. Values from ``0`` to ``32767`` are safe in all
    
  1279. databases supported by Django.
    
  1280. 
    
  1281. ``SlugField``
    
  1282. -------------
    
  1283. 
    
  1284. .. class:: SlugField(max_length=50, **options)
    
  1285. 
    
  1286. :term:`Slug <slug>` is a newspaper term. A slug is a short label for something,
    
  1287. containing only letters, numbers, underscores or hyphens. They're generally used
    
  1288. in URLs.
    
  1289. 
    
  1290. Like a CharField, you can specify :attr:`~CharField.max_length` (read the note
    
  1291. about database portability and :attr:`~CharField.max_length` in that section,
    
  1292. too). If :attr:`~CharField.max_length` is not specified, Django will use a
    
  1293. default length of 50.
    
  1294. 
    
  1295. Implies setting :attr:`Field.db_index` to ``True``.
    
  1296. 
    
  1297. It is often useful to automatically prepopulate a SlugField based on the value
    
  1298. of some other value.  You can do this automatically in the admin using
    
  1299. :attr:`~django.contrib.admin.ModelAdmin.prepopulated_fields`.
    
  1300. 
    
  1301. It uses :class:`~django.core.validators.validate_slug` or
    
  1302. :class:`~django.core.validators.validate_unicode_slug` for validation.
    
  1303. 
    
  1304. .. attribute:: SlugField.allow_unicode
    
  1305. 
    
  1306.     If ``True``, the field accepts Unicode letters in addition to ASCII
    
  1307.     letters. Defaults to ``False``.
    
  1308. 
    
  1309. ``SmallAutoField``
    
  1310. ------------------
    
  1311. 
    
  1312. .. class:: SmallAutoField(**options)
    
  1313. 
    
  1314. Like an :class:`AutoField`, but only allows values under a certain
    
  1315. (database-dependent) limit. Values from ``1`` to ``32767`` are safe in all
    
  1316. databases supported by Django.
    
  1317. 
    
  1318. ``SmallIntegerField``
    
  1319. ---------------------
    
  1320. 
    
  1321. .. class:: SmallIntegerField(**options)
    
  1322. 
    
  1323. Like an :class:`IntegerField`, but only allows values under a certain
    
  1324. (database-dependent) point. Values from ``-32768`` to ``32767`` are safe in all
    
  1325. databases supported by Django.
    
  1326. 
    
  1327. ``TextField``
    
  1328. -------------
    
  1329. 
    
  1330. .. class:: TextField(**options)
    
  1331. 
    
  1332. A large text field. The default form widget for this field is a
    
  1333. :class:`~django.forms.Textarea`.
    
  1334. 
    
  1335. If you specify a ``max_length`` attribute, it will be reflected in the
    
  1336. :class:`~django.forms.Textarea` widget of the auto-generated form field.
    
  1337. However it is not enforced at the model or database level. Use a
    
  1338. :class:`CharField` for that.
    
  1339. 
    
  1340. .. attribute:: TextField.db_collation
    
  1341. 
    
  1342.     Optional. The database collation name of the field.
    
  1343. 
    
  1344.     .. note::
    
  1345. 
    
  1346.         Collation names are not standardized. As such, this will not be
    
  1347.         portable across multiple database backends.
    
  1348. 
    
  1349.     .. admonition:: Oracle
    
  1350. 
    
  1351.         Oracle does not support collations for a ``TextField``.
    
  1352. 
    
  1353. ``TimeField``
    
  1354. -------------
    
  1355. 
    
  1356. .. class:: TimeField(auto_now=False, auto_now_add=False, **options)
    
  1357. 
    
  1358. A time, represented in Python by a ``datetime.time`` instance. Accepts the same
    
  1359. auto-population options as :class:`DateField`.
    
  1360. 
    
  1361. The default form widget for this field is a :class:`~django.forms.TimeInput`.
    
  1362. The admin adds some JavaScript shortcuts.
    
  1363. 
    
  1364. ``URLField``
    
  1365. ------------
    
  1366. 
    
  1367. .. class:: URLField(max_length=200, **options)
    
  1368. 
    
  1369. A :class:`CharField` for a URL, validated by
    
  1370. :class:`~django.core.validators.URLValidator`.
    
  1371. 
    
  1372. The default form widget for this field is a :class:`~django.forms.URLInput`.
    
  1373. 
    
  1374. Like all :class:`CharField` subclasses, :class:`URLField` takes the optional
    
  1375. :attr:`~CharField.max_length` argument. If you don't specify
    
  1376. :attr:`~CharField.max_length`, a default of 200 is used.
    
  1377. 
    
  1378. ``UUIDField``
    
  1379. -------------
    
  1380. 
    
  1381. .. class:: UUIDField(**options)
    
  1382. 
    
  1383. A field for storing universally unique identifiers. Uses Python's
    
  1384. :class:`~python:uuid.UUID` class. When used on PostgreSQL, this stores in a
    
  1385. ``uuid`` datatype, otherwise in a ``char(32)``.
    
  1386. 
    
  1387. Universally unique identifiers are a good alternative to :class:`AutoField` for
    
  1388. :attr:`~Field.primary_key`. The database will not generate the UUID for you, so
    
  1389. it is recommended to use :attr:`~Field.default`::
    
  1390. 
    
  1391.     import uuid
    
  1392.     from django.db import models
    
  1393. 
    
  1394.     class MyUUIDModel(models.Model):
    
  1395.         id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    
  1396.         # other fields
    
  1397. 
    
  1398. Note that a callable (with the parentheses omitted) is passed to ``default``,
    
  1399. not an instance of ``UUID``.
    
  1400. 
    
  1401. .. admonition:: Lookups on PostgreSQL
    
  1402. 
    
  1403.     Using :lookup:`iexact`, :lookup:`contains`, :lookup:`icontains`,
    
  1404.     :lookup:`startswith`, :lookup:`istartswith`, :lookup:`endswith`, or
    
  1405.     :lookup:`iendswith` lookups on PostgreSQL don't work for values without
    
  1406.     hyphens, because PostgreSQL stores them in a hyphenated uuid datatype type.
    
  1407. 
    
  1408. Relationship fields
    
  1409. ===================
    
  1410. 
    
  1411. .. module:: django.db.models.fields.related
    
  1412.    :synopsis: Related field types
    
  1413. 
    
  1414. .. currentmodule:: django.db.models
    
  1415. 
    
  1416. Django also defines a set of fields that represent relations.
    
  1417. 
    
  1418. .. _ref-foreignkey:
    
  1419. 
    
  1420. ``ForeignKey``
    
  1421. --------------
    
  1422. 
    
  1423. .. class:: ForeignKey(to, on_delete, **options)
    
  1424. 
    
  1425. A many-to-one relationship. Requires two positional arguments: the class to
    
  1426. which the model is related and the :attr:`~ForeignKey.on_delete` option.
    
  1427. 
    
  1428. .. _recursive-relationships:
    
  1429. 
    
  1430. To create a recursive relationship -- an object that has a many-to-one
    
  1431. relationship with itself -- use ``models.ForeignKey('self',
    
  1432. on_delete=models.CASCADE)``.
    
  1433. 
    
  1434. .. _lazy-relationships:
    
  1435. 
    
  1436. If you need to create a relationship on a model that has not yet been defined,
    
  1437. you can use the name of the model, rather than the model object itself::
    
  1438. 
    
  1439.     from django.db import models
    
  1440. 
    
  1441.     class Car(models.Model):
    
  1442.         manufacturer = models.ForeignKey(
    
  1443.             'Manufacturer',
    
  1444.             on_delete=models.CASCADE,
    
  1445.         )
    
  1446.         # ...
    
  1447. 
    
  1448.     class Manufacturer(models.Model):
    
  1449.         # ...
    
  1450.         pass
    
  1451. 
    
  1452. Relationships defined this way on :ref:`abstract models
    
  1453. <abstract-base-classes>` are resolved when the model is subclassed as a
    
  1454. concrete model and are not relative to the abstract model's ``app_label``:
    
  1455. 
    
  1456. .. code-block:: python
    
  1457.     :caption: ``products/models.py``
    
  1458. 
    
  1459.     from django.db import models
    
  1460. 
    
  1461.     class AbstractCar(models.Model):
    
  1462.         manufacturer = models.ForeignKey('Manufacturer', on_delete=models.CASCADE)
    
  1463. 
    
  1464.         class Meta:
    
  1465.             abstract = True
    
  1466. 
    
  1467. .. code-block:: python
    
  1468.     :caption: ``production/models.py``
    
  1469. 
    
  1470.     from django.db import models
    
  1471.     from products.models import AbstractCar
    
  1472. 
    
  1473.     class Manufacturer(models.Model):
    
  1474.         pass
    
  1475. 
    
  1476.     class Car(AbstractCar):
    
  1477.         pass
    
  1478. 
    
  1479.     # Car.manufacturer will point to `production.Manufacturer` here.
    
  1480. 
    
  1481. To refer to models defined in another application, you can explicitly specify
    
  1482. a model with the full application label. For example, if the ``Manufacturer``
    
  1483. model above is defined in another application called ``production``, you'd
    
  1484. need to use::
    
  1485. 
    
  1486.     class Car(models.Model):
    
  1487.         manufacturer = models.ForeignKey(
    
  1488.             'production.Manufacturer',
    
  1489.             on_delete=models.CASCADE,
    
  1490.         )
    
  1491. 
    
  1492. This sort of reference, called a lazy relationship, can be useful when
    
  1493. resolving circular import dependencies between two applications.
    
  1494. 
    
  1495. A database index is automatically created on the ``ForeignKey``. You can
    
  1496. disable this by setting :attr:`~Field.db_index` to ``False``.  You may want to
    
  1497. avoid the overhead of an index if you are creating a foreign key for
    
  1498. consistency rather than joins, or if you will be creating an alternative index
    
  1499. like a partial or multiple column index.
    
  1500. 
    
  1501. Database Representation
    
  1502. ~~~~~~~~~~~~~~~~~~~~~~~
    
  1503. 
    
  1504. Behind the scenes, Django appends ``"_id"`` to the field name to create its
    
  1505. database column name. In the above example, the database table for the ``Car``
    
  1506. model will have a ``manufacturer_id`` column. (You can change this explicitly by
    
  1507. specifying :attr:`~Field.db_column`) However, your code should never have to
    
  1508. deal with the database column name, unless you write custom SQL. You'll always
    
  1509. deal with the field names of your model object.
    
  1510. 
    
  1511. .. _foreign-key-arguments:
    
  1512. 
    
  1513. Arguments
    
  1514. ~~~~~~~~~
    
  1515. 
    
  1516. :class:`ForeignKey` accepts other arguments that define the details of how the
    
  1517. relation works.
    
  1518. 
    
  1519. .. attribute:: ForeignKey.on_delete
    
  1520. 
    
  1521.     When an object referenced by a :class:`ForeignKey` is deleted, Django will
    
  1522.     emulate the behavior of the SQL constraint specified by the
    
  1523.     :attr:`on_delete` argument. For example, if you have a nullable
    
  1524.     :class:`ForeignKey` and you want it to be set null when the referenced
    
  1525.     object is deleted::
    
  1526. 
    
  1527.         user = models.ForeignKey(
    
  1528.             User,
    
  1529.             models.SET_NULL,
    
  1530.             blank=True,
    
  1531.             null=True,
    
  1532.         )
    
  1533. 
    
  1534.     ``on_delete`` doesn't create an SQL constraint in the database. Support for
    
  1535.     database-level cascade options :ticket:`may be implemented later <21961>`.
    
  1536. 
    
  1537. The possible values for :attr:`~ForeignKey.on_delete` are found in
    
  1538. :mod:`django.db.models`:
    
  1539. 
    
  1540. * .. attribute:: CASCADE
    
  1541. 
    
  1542.     Cascade deletes. Django emulates the behavior of the SQL constraint ON
    
  1543.     DELETE CASCADE and also deletes the object containing the ForeignKey.
    
  1544. 
    
  1545.     :meth:`.Model.delete` isn't called on related models, but the
    
  1546.     :data:`~django.db.models.signals.pre_delete` and
    
  1547.     :data:`~django.db.models.signals.post_delete` signals are sent for all
    
  1548.     deleted objects.
    
  1549. 
    
  1550. * .. attribute:: PROTECT
    
  1551. 
    
  1552.     Prevent deletion of the referenced object by raising
    
  1553.     :exc:`~django.db.models.ProtectedError`, a subclass of
    
  1554.     :exc:`django.db.IntegrityError`.
    
  1555. 
    
  1556. * .. attribute:: RESTRICT
    
  1557. 
    
  1558.     Prevent deletion of the referenced object by raising
    
  1559.     :exc:`~django.db.models.RestrictedError` (a subclass of
    
  1560.     :exc:`django.db.IntegrityError`). Unlike :attr:`PROTECT`, deletion of the
    
  1561.     referenced object is allowed if it also references a different object
    
  1562.     that is being deleted in the same operation, but via a :attr:`CASCADE`
    
  1563.     relationship.
    
  1564. 
    
  1565.     Consider this set of models::
    
  1566. 
    
  1567.         class Artist(models.Model):
    
  1568.             name = models.CharField(max_length=10)
    
  1569. 
    
  1570.         class Album(models.Model):
    
  1571.             artist = models.ForeignKey(Artist, on_delete=models.CASCADE)
    
  1572. 
    
  1573.         class Song(models.Model):
    
  1574.             artist = models.ForeignKey(Artist, on_delete=models.CASCADE)
    
  1575.             album = models.ForeignKey(Album, on_delete=models.RESTRICT)
    
  1576. 
    
  1577.     ``Artist`` can be deleted even if that implies deleting an ``Album``
    
  1578.     which is referenced by a ``Song``, because ``Song`` also references
    
  1579.     ``Artist`` itself through a cascading relationship. For example::
    
  1580. 
    
  1581.         >>> artist_one = Artist.objects.create(name='artist one')
    
  1582.         >>> artist_two = Artist.objects.create(name='artist two')
    
  1583.         >>> album_one = Album.objects.create(artist=artist_one)
    
  1584.         >>> album_two = Album.objects.create(artist=artist_two)
    
  1585.         >>> song_one = Song.objects.create(artist=artist_one, album=album_one)
    
  1586.         >>> song_two = Song.objects.create(artist=artist_one, album=album_two)
    
  1587.         >>> album_one.delete()
    
  1588.         # Raises RestrictedError.
    
  1589.         >>> artist_two.delete()
    
  1590.         # Raises RestrictedError.
    
  1591.         >>> artist_one.delete()
    
  1592.         (4, {'Song': 2, 'Album': 1, 'Artist': 1})
    
  1593. 
    
  1594. * .. attribute:: SET_NULL
    
  1595. 
    
  1596.     Set the :class:`ForeignKey` null; this is only possible if
    
  1597.     :attr:`~Field.null` is ``True``.
    
  1598. 
    
  1599. * .. attribute:: SET_DEFAULT
    
  1600. 
    
  1601.     Set the :class:`ForeignKey` to its default value; a default for the
    
  1602.     :class:`ForeignKey` must be set.
    
  1603. 
    
  1604. * .. function:: SET()
    
  1605. 
    
  1606.     Set the :class:`ForeignKey` to the value passed to
    
  1607.     :func:`~django.db.models.SET()`, or if a callable is passed in,
    
  1608.     the result of calling it. In most cases, passing a callable will be
    
  1609.     necessary to avoid executing queries at the time your ``models.py`` is
    
  1610.     imported::
    
  1611. 
    
  1612.         from django.conf import settings
    
  1613.         from django.contrib.auth import get_user_model
    
  1614.         from django.db import models
    
  1615. 
    
  1616.         def get_sentinel_user():
    
  1617.             return get_user_model().objects.get_or_create(username='deleted')[0]
    
  1618. 
    
  1619.         class MyModel(models.Model):
    
  1620.             user = models.ForeignKey(
    
  1621.                 settings.AUTH_USER_MODEL,
    
  1622.                 on_delete=models.SET(get_sentinel_user),
    
  1623.             )
    
  1624. 
    
  1625. * .. attribute:: DO_NOTHING
    
  1626. 
    
  1627.     Take no action. If your database backend enforces referential
    
  1628.     integrity, this will cause an :exc:`~django.db.IntegrityError` unless
    
  1629.     you manually add an SQL ``ON DELETE`` constraint to the database field.
    
  1630. 
    
  1631. .. attribute:: ForeignKey.limit_choices_to
    
  1632. 
    
  1633.     Sets a limit to the available choices for this field when this field is
    
  1634.     rendered using a ``ModelForm`` or the admin (by default, all objects
    
  1635.     in the queryset are available to choose). Either a dictionary, a
    
  1636.     :class:`~django.db.models.Q` object, or a callable returning a
    
  1637.     dictionary or :class:`~django.db.models.Q` object can be used.
    
  1638. 
    
  1639.     For example::
    
  1640. 
    
  1641.         staff_member = models.ForeignKey(
    
  1642.             User,
    
  1643.             on_delete=models.CASCADE,
    
  1644.             limit_choices_to={'is_staff': True},
    
  1645.         )
    
  1646. 
    
  1647.     causes the corresponding field on the ``ModelForm`` to list only ``Users``
    
  1648.     that have ``is_staff=True``. This may be helpful in the Django admin.
    
  1649. 
    
  1650.     The callable form can be helpful, for instance, when used in conjunction
    
  1651.     with the Python ``datetime`` module to limit selections by date range. For
    
  1652.     example::
    
  1653. 
    
  1654.         def limit_pub_date_choices():
    
  1655.             return {'pub_date__lte': datetime.date.today()}
    
  1656. 
    
  1657.         limit_choices_to = limit_pub_date_choices
    
  1658. 
    
  1659.     If ``limit_choices_to`` is or returns a :class:`Q object
    
  1660.     <django.db.models.Q>`, which is useful for :ref:`complex queries
    
  1661.     <complex-lookups-with-q>`, then it will only have an effect on the choices
    
  1662.     available in the admin when the field is not listed in
    
  1663.     :attr:`~django.contrib.admin.ModelAdmin.raw_id_fields` in the
    
  1664.     ``ModelAdmin`` for the model.
    
  1665. 
    
  1666.     .. note::
    
  1667. 
    
  1668.         If a callable is used for ``limit_choices_to``, it will be invoked
    
  1669.         every time a new form is instantiated. It may also be invoked when a
    
  1670.         model is validated, for example by management commands or the admin.
    
  1671.         The admin constructs querysets to validate its form inputs in various
    
  1672.         edge cases multiple times, so there is a possibility your callable may
    
  1673.         be invoked several times.
    
  1674. 
    
  1675. .. attribute:: ForeignKey.related_name
    
  1676. 
    
  1677.     The name to use for the relation from the related object back to this one.
    
  1678.     It's also the default value for :attr:`related_query_name` (the name to use
    
  1679.     for the reverse filter name from the target model). See the :ref:`related
    
  1680.     objects documentation <backwards-related-objects>` for a full explanation
    
  1681.     and example. Note that you must set this value when defining relations on
    
  1682.     :ref:`abstract models <abstract-base-classes>`; and when you do so
    
  1683.     :ref:`some special syntax <abstract-related-name>` is available.
    
  1684. 
    
  1685.     If you'd prefer Django not to create a backwards relation, set
    
  1686.     ``related_name`` to ``'+'`` or end it with ``'+'``. For example, this will
    
  1687.     ensure that the ``User`` model won't have a backwards relation to this
    
  1688.     model::
    
  1689. 
    
  1690.         user = models.ForeignKey(
    
  1691.             User,
    
  1692.             on_delete=models.CASCADE,
    
  1693.             related_name='+',
    
  1694.         )
    
  1695. 
    
  1696. .. attribute:: ForeignKey.related_query_name
    
  1697. 
    
  1698.     The name to use for the reverse filter name from the target model. It
    
  1699.     defaults to the value of :attr:`related_name` or
    
  1700.     :attr:`~django.db.models.Options.default_related_name` if set, otherwise it
    
  1701.     defaults to the name of the model::
    
  1702. 
    
  1703.         # Declare the ForeignKey with related_query_name
    
  1704.         class Tag(models.Model):
    
  1705.             article = models.ForeignKey(
    
  1706.                 Article,
    
  1707.                 on_delete=models.CASCADE,
    
  1708.                 related_name="tags",
    
  1709.                 related_query_name="tag",
    
  1710.             )
    
  1711.             name = models.CharField(max_length=255)
    
  1712. 
    
  1713.         # That's now the name of the reverse filter
    
  1714.         Article.objects.filter(tag__name="important")
    
  1715. 
    
  1716.     Like :attr:`related_name`, ``related_query_name`` supports app label and
    
  1717.     class interpolation via :ref:`some special syntax <abstract-related-name>`.
    
  1718. 
    
  1719. .. attribute:: ForeignKey.to_field
    
  1720. 
    
  1721.     The field on the related object that the relation is to. By default, Django
    
  1722.     uses the primary key of the related object. If you reference a different
    
  1723.     field, that field must have ``unique=True``.
    
  1724. 
    
  1725. .. attribute:: ForeignKey.db_constraint
    
  1726. 
    
  1727.     Controls whether or not a constraint should be created in the database for
    
  1728.     this foreign key. The default is ``True``, and that's almost certainly what
    
  1729.     you want; setting this to ``False`` can be very bad for data integrity.
    
  1730.     That said, here are some scenarios where you might want to do this:
    
  1731. 
    
  1732.     * You have legacy data that is not valid.
    
  1733.     * You're sharding your database.
    
  1734. 
    
  1735.     If this is set to ``False``, accessing a related object that doesn't exist
    
  1736.     will raise its ``DoesNotExist`` exception.
    
  1737. 
    
  1738. .. attribute:: ForeignKey.swappable
    
  1739. 
    
  1740.     Controls the migration framework's reaction if this :class:`ForeignKey`
    
  1741.     is pointing at a swappable model. If it is ``True`` - the default -
    
  1742.     then if the :class:`ForeignKey` is pointing at a model which matches
    
  1743.     the current value of ``settings.AUTH_USER_MODEL`` (or another swappable
    
  1744.     model setting) the relationship will be stored in the migration using
    
  1745.     a reference to the setting, not to the model directly.
    
  1746. 
    
  1747.     You only want to override this to be ``False`` if you are sure your
    
  1748.     model should always point toward the swapped-in model - for example,
    
  1749.     if it is a profile model designed specifically for your custom user model.
    
  1750. 
    
  1751.     Setting it to ``False`` does not mean you can reference a swappable model
    
  1752.     even if it is swapped out - ``False`` means that the migrations made
    
  1753.     with this ForeignKey will always reference the exact model you specify
    
  1754.     (so it will fail hard if the user tries to run with a User model you don't
    
  1755.     support, for example).
    
  1756. 
    
  1757.     If in doubt, leave it to its default of ``True``.
    
  1758. 
    
  1759. ``ManyToManyField``
    
  1760. -------------------
    
  1761. 
    
  1762. .. class:: ManyToManyField(to, **options)
    
  1763. 
    
  1764. A many-to-many relationship. Requires a positional argument: the class to
    
  1765. which the model is related, which works exactly the same as it does for
    
  1766. :class:`ForeignKey`, including :ref:`recursive <recursive-relationships>` and
    
  1767. :ref:`lazy <lazy-relationships>` relationships.
    
  1768. 
    
  1769. Related objects can be added, removed, or created with the field's
    
  1770. :class:`~django.db.models.fields.related.RelatedManager`.
    
  1771. 
    
  1772. Database Representation
    
  1773. ~~~~~~~~~~~~~~~~~~~~~~~
    
  1774. 
    
  1775. Behind the scenes, Django creates an intermediary join table to represent the
    
  1776. many-to-many relationship. By default, this table name is generated using the
    
  1777. name of the many-to-many field and the name of the table for the model that
    
  1778. contains it. Since some databases don't support table names above a certain
    
  1779. length, these table names will be automatically truncated and a uniqueness hash
    
  1780. will be used, e.g. ``author_books_9cdf``. You can manually provide the name of
    
  1781. the join table using the :attr:`~ManyToManyField.db_table` option.
    
  1782. 
    
  1783. .. _manytomany-arguments:
    
  1784. 
    
  1785. Arguments
    
  1786. ~~~~~~~~~
    
  1787. 
    
  1788. :class:`ManyToManyField` accepts an extra set of arguments -- all optional --
    
  1789. that control how the relationship functions.
    
  1790. 
    
  1791. .. attribute:: ManyToManyField.related_name
    
  1792. 
    
  1793.     Same as :attr:`ForeignKey.related_name`.
    
  1794. 
    
  1795. .. attribute:: ManyToManyField.related_query_name
    
  1796. 
    
  1797.     Same as :attr:`ForeignKey.related_query_name`.
    
  1798. 
    
  1799. .. attribute:: ManyToManyField.limit_choices_to
    
  1800. 
    
  1801.     Same as :attr:`ForeignKey.limit_choices_to`.
    
  1802. 
    
  1803. .. attribute:: ManyToManyField.symmetrical
    
  1804. 
    
  1805.     Only used in the definition of ManyToManyFields on self. Consider the
    
  1806.     following model::
    
  1807. 
    
  1808.         from django.db import models
    
  1809. 
    
  1810.         class Person(models.Model):
    
  1811.             friends = models.ManyToManyField("self")
    
  1812. 
    
  1813.     When Django processes this model, it identifies that it has a
    
  1814.     :class:`ManyToManyField` on itself, and as a result, it doesn't add a
    
  1815.     ``person_set`` attribute to the ``Person`` class. Instead, the
    
  1816.     :class:`ManyToManyField` is assumed to be symmetrical -- that is, if I am
    
  1817.     your friend, then you are my friend.
    
  1818. 
    
  1819.     If you do not want symmetry in many-to-many relationships with ``self``, set
    
  1820.     :attr:`~ManyToManyField.symmetrical` to ``False``. This will force Django to
    
  1821.     add the descriptor for the reverse relationship, allowing
    
  1822.     :class:`ManyToManyField` relationships to be non-symmetrical.
    
  1823. 
    
  1824. .. attribute:: ManyToManyField.through
    
  1825. 
    
  1826.     Django will automatically generate a table to manage many-to-many
    
  1827.     relationships. However, if you want to manually specify the intermediary
    
  1828.     table, you can use the :attr:`~ManyToManyField.through` option to specify
    
  1829.     the Django model that represents the intermediate table that you want to
    
  1830.     use.
    
  1831. 
    
  1832.     The most common use for this option is when you want to associate
    
  1833.     :ref:`extra data with a many-to-many relationship
    
  1834.     <intermediary-manytomany>`.
    
  1835. 
    
  1836.     .. note::
    
  1837. 
    
  1838.         If you don't want multiple associations between the same instances, add
    
  1839.         a :class:`~django.db.models.UniqueConstraint` including the from and to
    
  1840.         fields. Django's automatically generated many-to-many tables include
    
  1841.         such a constraint.
    
  1842. 
    
  1843.     .. note::
    
  1844. 
    
  1845.         Recursive relationships using an intermediary model can't determine the
    
  1846.         reverse accessors names, as they would be the same. You need to set a
    
  1847.         :attr:`~ForeignKey.related_name` to at least one of them. If you'd
    
  1848.         prefer Django not to create a backwards relation, set ``related_name``
    
  1849.         to ``'+'``.
    
  1850. 
    
  1851.     If you don't specify an explicit ``through`` model, there is still an
    
  1852.     implicit ``through`` model class you can use to directly access the table
    
  1853.     created to hold the association. It has three fields to link the models.
    
  1854. 
    
  1855.     If the source and target models differ, the following fields are
    
  1856.     generated:
    
  1857. 
    
  1858.     * ``id``: the primary key of the relation.
    
  1859.     * ``<containing_model>_id``: the ``id`` of the model that declares the
    
  1860.       ``ManyToManyField``.
    
  1861.     * ``<other_model>_id``: the ``id`` of the model that the
    
  1862.       ``ManyToManyField`` points to.
    
  1863. 
    
  1864.     If the ``ManyToManyField`` points from and to the same model, the following
    
  1865.     fields are generated:
    
  1866. 
    
  1867.     * ``id``: the primary key of the relation.
    
  1868.     * ``from_<model>_id``: the ``id`` of the instance which points at the
    
  1869.       model (i.e. the source instance).
    
  1870.     * ``to_<model>_id``: the ``id`` of the instance to which the relationship
    
  1871.       points (i.e. the target model instance).
    
  1872. 
    
  1873.     This class can be used to query associated records for a given model
    
  1874.     instance like a normal model::
    
  1875. 
    
  1876.         Model.m2mfield.through.objects.all()
    
  1877. 
    
  1878. .. attribute:: ManyToManyField.through_fields
    
  1879. 
    
  1880.     Only used when a custom intermediary model is specified. Django will
    
  1881.     normally determine which fields of the intermediary model to use in order
    
  1882.     to establish a many-to-many relationship automatically. However,
    
  1883.     consider the following models::
    
  1884. 
    
  1885.         from django.db import models
    
  1886. 
    
  1887.         class Person(models.Model):
    
  1888.             name = models.CharField(max_length=50)
    
  1889. 
    
  1890.         class Group(models.Model):
    
  1891.             name = models.CharField(max_length=128)
    
  1892.             members = models.ManyToManyField(
    
  1893.                 Person,
    
  1894.                 through='Membership',
    
  1895.                 through_fields=('group', 'person'),
    
  1896.             )
    
  1897. 
    
  1898.         class Membership(models.Model):
    
  1899.             group = models.ForeignKey(Group, on_delete=models.CASCADE)
    
  1900.             person = models.ForeignKey(Person, on_delete=models.CASCADE)
    
  1901.             inviter = models.ForeignKey(
    
  1902.                 Person,
    
  1903.                 on_delete=models.CASCADE,
    
  1904.                 related_name="membership_invites",
    
  1905.             )
    
  1906.             invite_reason = models.CharField(max_length=64)
    
  1907. 
    
  1908.     ``Membership`` has *two* foreign keys to ``Person`` (``person`` and
    
  1909.     ``inviter``), which makes the relationship ambiguous and Django can't know
    
  1910.     which one to use. In this case, you must explicitly specify which
    
  1911.     foreign keys Django should use using ``through_fields``, as in the example
    
  1912.     above.
    
  1913. 
    
  1914.     ``through_fields`` accepts a 2-tuple ``('field1', 'field2')``, where
    
  1915.     ``field1`` is the name of the foreign key to the model the
    
  1916.     :class:`ManyToManyField` is defined on (``group`` in this case), and
    
  1917.     ``field2`` the name of the foreign key to the target model (``person``
    
  1918.     in this case).
    
  1919. 
    
  1920.     When you have more than one foreign key on an intermediary model to any
    
  1921.     (or even both) of the models participating in a many-to-many relationship,
    
  1922.     you *must* specify ``through_fields``. This also applies to
    
  1923.     :ref:`recursive relationships <recursive-relationships>`
    
  1924.     when an intermediary model is used and there are more than two
    
  1925.     foreign keys to the model, or you want to explicitly specify which two
    
  1926.     Django should use.
    
  1927. 
    
  1928. .. attribute:: ManyToManyField.db_table
    
  1929. 
    
  1930.     The name of the table to create for storing the many-to-many data. If this
    
  1931.     is not provided, Django will assume a default name based upon the names of:
    
  1932.     the table for the model defining the relationship and the name of the field
    
  1933.     itself.
    
  1934. 
    
  1935. .. attribute:: ManyToManyField.db_constraint
    
  1936. 
    
  1937.     Controls whether or not constraints should be created in the database for
    
  1938.     the foreign keys in the intermediary table. The default is ``True``, and
    
  1939.     that's almost certainly what you want; setting this to ``False`` can be
    
  1940.     very bad for data integrity. That said, here are some scenarios where you
    
  1941.     might want to do this:
    
  1942. 
    
  1943.     * You have legacy data that is not valid.
    
  1944.     * You're sharding your database.
    
  1945. 
    
  1946.     It is an error to pass both ``db_constraint`` and ``through``.
    
  1947. 
    
  1948. .. attribute:: ManyToManyField.swappable
    
  1949. 
    
  1950.     Controls the migration framework's reaction if this :class:`ManyToManyField`
    
  1951.     is pointing at a swappable model. If it is ``True`` - the default -
    
  1952.     then if the :class:`ManyToManyField` is pointing at a model which matches
    
  1953.     the current value of ``settings.AUTH_USER_MODEL`` (or another swappable
    
  1954.     model setting) the relationship will be stored in the migration using
    
  1955.     a reference to the setting, not to the model directly.
    
  1956. 
    
  1957.     You only want to override this to be ``False`` if you are sure your
    
  1958.     model should always point toward the swapped-in model - for example,
    
  1959.     if it is a profile model designed specifically for your custom user model.
    
  1960. 
    
  1961.     If in doubt, leave it to its default of ``True``.
    
  1962. 
    
  1963. :class:`ManyToManyField` does not support :attr:`~Field.validators`.
    
  1964. 
    
  1965. :attr:`~Field.null` has no effect since there is no way to require a
    
  1966. relationship at the database level.
    
  1967. 
    
  1968. ``OneToOneField``
    
  1969. -----------------
    
  1970. 
    
  1971. .. class:: OneToOneField(to, on_delete, parent_link=False, **options)
    
  1972. 
    
  1973. A one-to-one relationship. Conceptually, this is similar to a
    
  1974. :class:`ForeignKey` with :attr:`unique=True <Field.unique>`, but the
    
  1975. "reverse" side of the relation will directly return a single object.
    
  1976. 
    
  1977. This is most useful as the primary key of a model which "extends"
    
  1978. another model in some way; :ref:`multi-table-inheritance` is
    
  1979. implemented by adding an implicit one-to-one relation from the child
    
  1980. model to the parent model, for example.
    
  1981. 
    
  1982. One positional argument is required: the class to which the model will be
    
  1983. related. This works exactly the same as it does for :class:`ForeignKey`,
    
  1984. including all the options regarding :ref:`recursive <recursive-relationships>`
    
  1985. and :ref:`lazy <lazy-relationships>` relationships.
    
  1986. 
    
  1987. If you do not specify the :attr:`~ForeignKey.related_name` argument for the
    
  1988. ``OneToOneField``, Django will use the lowercase name of the current model as
    
  1989. default value.
    
  1990. 
    
  1991. With the following example::
    
  1992. 
    
  1993.     from django.conf import settings
    
  1994.     from django.db import models
    
  1995. 
    
  1996.     class MySpecialUser(models.Model):
    
  1997.         user = models.OneToOneField(
    
  1998.             settings.AUTH_USER_MODEL,
    
  1999.             on_delete=models.CASCADE,
    
  2000.         )
    
  2001.         supervisor = models.OneToOneField(
    
  2002.             settings.AUTH_USER_MODEL,
    
  2003.             on_delete=models.CASCADE,
    
  2004.             related_name='supervisor_of',
    
  2005.         )
    
  2006. 
    
  2007. your resulting ``User`` model will have the following attributes::
    
  2008. 
    
  2009.     >>> user = User.objects.get(pk=1)
    
  2010.     >>> hasattr(user, 'myspecialuser')
    
  2011.     True
    
  2012.     >>> hasattr(user, 'supervisor_of')
    
  2013.     True
    
  2014. 
    
  2015. A ``RelatedObjectDoesNotExist`` exception is raised when accessing the reverse
    
  2016. relationship if an entry in the related table doesn't exist. This is a subclass
    
  2017. of the target model's :exc:`Model.DoesNotExist
    
  2018. <django.db.models.Model.DoesNotExist>` exception and can be accessed as an
    
  2019. attribute of the reverse accessor. For example, if a user doesn't have a
    
  2020. supervisor designated by ``MySpecialUser``::
    
  2021. 
    
  2022.     try:
    
  2023.         user.supervisor_of
    
  2024.     except User.supervisor_of.RelatedObjectDoesNotExist:
    
  2025.         pass
    
  2026. 
    
  2027. .. _onetoone-arguments:
    
  2028. 
    
  2029. Additionally, ``OneToOneField`` accepts all of the extra arguments
    
  2030. accepted by :class:`ForeignKey`, plus one extra argument:
    
  2031. 
    
  2032. .. attribute:: OneToOneField.parent_link
    
  2033. 
    
  2034.     When ``True`` and used in a model which inherits from another
    
  2035.     :term:`concrete model`, indicates that this field should be used as the
    
  2036.     link back to the parent class, rather than the extra
    
  2037.     ``OneToOneField`` which would normally be implicitly created by
    
  2038.     subclassing.
    
  2039. 
    
  2040. See :doc:`One-to-one relationships </topics/db/examples/one_to_one>` for usage
    
  2041. examples of ``OneToOneField``.
    
  2042. 
    
  2043. Field API reference
    
  2044. ===================
    
  2045. 
    
  2046. .. class:: Field
    
  2047. 
    
  2048.     ``Field`` is an abstract class that represents a database table column.
    
  2049.     Django uses fields to create the database table (:meth:`db_type`), to map
    
  2050.     Python types to database (:meth:`get_prep_value`) and vice-versa
    
  2051.     (:meth:`from_db_value`).
    
  2052. 
    
  2053.     A field is thus a fundamental piece in different Django APIs, notably,
    
  2054.     :class:`models <django.db.models.Model>` and :class:`querysets
    
  2055.     <django.db.models.query.QuerySet>`.
    
  2056. 
    
  2057.     In models, a field is instantiated as a class attribute and represents a
    
  2058.     particular table column, see :doc:`/topics/db/models`. It has attributes
    
  2059.     such as :attr:`null` and :attr:`unique`, and methods that Django uses to
    
  2060.     map the field value to database-specific values.
    
  2061. 
    
  2062.     A ``Field`` is a subclass of
    
  2063.     :class:`~django.db.models.lookups.RegisterLookupMixin` and thus both
    
  2064.     :class:`~django.db.models.Transform` and
    
  2065.     :class:`~django.db.models.Lookup` can be registered on it to be used
    
  2066.     in ``QuerySet``\s (e.g. ``field_name__exact="foo"``). All :ref:`built-in
    
  2067.     lookups <field-lookups>` are registered by default.
    
  2068. 
    
  2069.     All of Django's built-in fields, such as :class:`CharField`, are particular
    
  2070.     implementations of ``Field``. If you need a custom field, you can either
    
  2071.     subclass any of the built-in fields or write a ``Field`` from scratch. In
    
  2072.     either case, see :doc:`/howto/custom-model-fields`.
    
  2073. 
    
  2074.     .. attribute:: description
    
  2075. 
    
  2076.         A verbose description of the field, e.g. for the
    
  2077.         :mod:`django.contrib.admindocs` application.
    
  2078. 
    
  2079.         The description can be of the form::
    
  2080. 
    
  2081.             description = _("String (up to %(max_length)s)")
    
  2082. 
    
  2083.         where the arguments are interpolated from the field's ``__dict__``.
    
  2084. 
    
  2085.     .. attribute:: descriptor_class
    
  2086. 
    
  2087.         A class implementing the :py:ref:`descriptor protocol <descriptors>`
    
  2088.         that is instantiated and assigned to the model instance attribute. The
    
  2089.         constructor must accept a single argument, the ``Field`` instance.
    
  2090.         Overriding this class attribute allows for customizing the get and set
    
  2091.         behavior.
    
  2092. 
    
  2093.     To map a ``Field`` to a database-specific type, Django exposes several
    
  2094.     methods:
    
  2095. 
    
  2096.     .. method:: get_internal_type()
    
  2097. 
    
  2098.         Returns a string naming this field for backend specific purposes.
    
  2099.         By default, it returns the class name.
    
  2100. 
    
  2101.         See :ref:`emulating-built-in-field-types` for usage in custom fields.
    
  2102. 
    
  2103.     .. method:: db_type(connection)
    
  2104. 
    
  2105.         Returns the database column data type for the :class:`Field`, taking
    
  2106.         into account the ``connection``.
    
  2107. 
    
  2108.         See :ref:`custom-database-types` for usage in custom fields.
    
  2109. 
    
  2110.     .. method:: rel_db_type(connection)
    
  2111. 
    
  2112.         Returns the database column data type for fields such as ``ForeignKey``
    
  2113.         and ``OneToOneField`` that point to the :class:`Field`, taking
    
  2114.         into account the ``connection``.
    
  2115. 
    
  2116.         See :ref:`custom-database-types` for usage in custom fields.
    
  2117. 
    
  2118.     There are three main situations where Django needs to interact with the
    
  2119.     database backend and fields:
    
  2120. 
    
  2121.     * when it queries the database (Python value -> database backend value)
    
  2122.     * when it loads data from the database (database backend value -> Python
    
  2123.       value)
    
  2124.     * when it saves to the database (Python value -> database backend value)
    
  2125. 
    
  2126.     When querying, :meth:`get_db_prep_value` and :meth:`get_prep_value` are used:
    
  2127. 
    
  2128.     .. method:: get_prep_value(value)
    
  2129. 
    
  2130.         ``value`` is the current value of the model's attribute, and the method
    
  2131.         should return data in a format that has been prepared for use as a
    
  2132.         parameter in a query.
    
  2133. 
    
  2134.         See :ref:`converting-python-objects-to-query-values` for usage.
    
  2135. 
    
  2136.     .. method:: get_db_prep_value(value, connection, prepared=False)
    
  2137. 
    
  2138.         Converts ``value`` to a backend-specific value. By default it returns
    
  2139.         ``value`` if ``prepared=True`` and :meth:`~Field.get_prep_value` if is
    
  2140.         ``False``.
    
  2141. 
    
  2142.         See :ref:`converting-query-values-to-database-values` for usage.
    
  2143. 
    
  2144.     When loading data, :meth:`from_db_value` is used:
    
  2145. 
    
  2146.     .. method:: from_db_value(value, expression, connection)
    
  2147. 
    
  2148.         Converts a value as returned by the database to a Python object. It is
    
  2149.         the reverse of :meth:`get_prep_value`.
    
  2150. 
    
  2151.         This method is not used for most built-in fields as the database
    
  2152.         backend already returns the correct Python type, or the backend itself
    
  2153.         does the conversion.
    
  2154. 
    
  2155.         ``expression`` is the same as ``self``.
    
  2156. 
    
  2157.         See :ref:`converting-values-to-python-objects` for usage.
    
  2158. 
    
  2159.         .. note::
    
  2160. 
    
  2161.             For performance reasons, ``from_db_value`` is not implemented as a
    
  2162.             no-op on fields which do not require it (all Django fields).
    
  2163.             Consequently you may not call ``super`` in your definition.
    
  2164. 
    
  2165.     When saving, :meth:`pre_save` and :meth:`get_db_prep_save` are used:
    
  2166. 
    
  2167.     .. method:: get_db_prep_save(value, connection)
    
  2168. 
    
  2169.         Same as the :meth:`get_db_prep_value`, but called when the field value
    
  2170.         must be *saved* to the database. By default returns
    
  2171.         :meth:`get_db_prep_value`.
    
  2172. 
    
  2173.     .. method:: pre_save(model_instance, add)
    
  2174. 
    
  2175.         Method called prior to :meth:`get_db_prep_save` to prepare the value
    
  2176.         before being saved (e.g. for :attr:`DateField.auto_now`).
    
  2177. 
    
  2178.         ``model_instance`` is the instance this field belongs to and ``add``
    
  2179.         is whether the instance is being saved to the database for the first
    
  2180.         time.
    
  2181. 
    
  2182.         It should return the value of the appropriate attribute from
    
  2183.         ``model_instance`` for this field. The attribute name is in
    
  2184.         ``self.attname`` (this is set up by :class:`~django.db.models.Field`).
    
  2185. 
    
  2186.         See :ref:`preprocessing-values-before-saving` for usage.
    
  2187. 
    
  2188.     Fields often receive their values as a different type, either from
    
  2189.     serialization or from forms.
    
  2190. 
    
  2191.     .. method:: to_python(value)
    
  2192. 
    
  2193.         Converts the value into the correct Python object. It acts as the
    
  2194.         reverse of :meth:`value_to_string`, and is also called in
    
  2195.         :meth:`~django.db.models.Model.clean`.
    
  2196. 
    
  2197.         See :ref:`converting-values-to-python-objects` for usage.
    
  2198. 
    
  2199.     Besides saving to the database, the field also needs to know how to
    
  2200.     serialize its value:
    
  2201. 
    
  2202.     .. method:: value_from_object(obj)
    
  2203. 
    
  2204.         Returns the field's value for the given model instance.
    
  2205. 
    
  2206.         This method is often used by :meth:`value_to_string`.
    
  2207. 
    
  2208.     .. method:: value_to_string(obj)
    
  2209. 
    
  2210.         Converts ``obj`` to a string. Used to serialize the value of the field.
    
  2211. 
    
  2212.         See :ref:`converting-model-field-to-serialization` for usage.
    
  2213. 
    
  2214.     When using :class:`model forms <django.forms.ModelForm>`, the ``Field``
    
  2215.     needs to know which form field it should be represented by:
    
  2216. 
    
  2217.     .. method:: formfield(form_class=None, choices_form_class=None, **kwargs)
    
  2218. 
    
  2219.         Returns the default :class:`django.forms.Field` of this field for
    
  2220.         :class:`~django.forms.ModelForm`.
    
  2221. 
    
  2222.         By default, if both ``form_class`` and ``choices_form_class`` are
    
  2223.         ``None``, it uses :class:`~django.forms.CharField`. If the field has
    
  2224.         :attr:`~django.db.models.Field.choices` and ``choices_form_class``
    
  2225.         isn't specified, it uses :class:`~django.forms.TypedChoiceField`.
    
  2226. 
    
  2227.         See :ref:`specifying-form-field-for-model-field` for usage.
    
  2228. 
    
  2229.     .. method:: deconstruct()
    
  2230. 
    
  2231.         Returns a 4-tuple with enough information to recreate the field:
    
  2232. 
    
  2233.         1. The name of the field on the model.
    
  2234.         2. The import path of the field (e.g. ``"django.db.models.IntegerField"``).
    
  2235.            This should be the most portable version, so less specific may be better.
    
  2236.         3. A list of positional arguments.
    
  2237.         4. A dict of keyword arguments.
    
  2238. 
    
  2239.         This method must be added to fields prior to 1.7 to migrate its data
    
  2240.         using :doc:`/topics/migrations`.
    
  2241. 
    
  2242. Registering and fetching lookups
    
  2243. ================================
    
  2244. 
    
  2245. ``Field`` implements the :ref:`lookup registration API <lookup-registration-api>`.
    
  2246. The API can be used to customize which lookups are available for a field class, and
    
  2247. how lookups are fetched from a field.
    
  2248. 
    
  2249. .. _model-field-attributes:
    
  2250. 
    
  2251. =========================
    
  2252. Field attribute reference
    
  2253. =========================
    
  2254. 
    
  2255. Every ``Field`` instance contains several attributes that allow
    
  2256. introspecting its behavior. Use these attributes instead of ``isinstance``
    
  2257. checks when you need to write code that depends on a field's functionality.
    
  2258. These attributes can be used together with the :ref:`Model._meta API
    
  2259. <model-meta-field-api>` to narrow down a search for specific field types.
    
  2260. Custom model fields should implement these flags.
    
  2261. 
    
  2262. Attributes for fields
    
  2263. =====================
    
  2264. 
    
  2265. .. attribute:: Field.auto_created
    
  2266. 
    
  2267.      Boolean flag that indicates if the field was automatically created, such
    
  2268.      as the ``OneToOneField`` used by model inheritance.
    
  2269. 
    
  2270. .. attribute:: Field.concrete
    
  2271. 
    
  2272.     Boolean flag that indicates if the field has a database column associated
    
  2273.     with it.
    
  2274. 
    
  2275. .. attribute:: Field.hidden
    
  2276. 
    
  2277.     Boolean flag that indicates if a field is used to back another non-hidden
    
  2278.     field's functionality (e.g. the ``content_type`` and ``object_id`` fields
    
  2279.     that make up a ``GenericForeignKey``). The ``hidden`` flag is used to
    
  2280.     distinguish what constitutes the public subset of fields on the model from
    
  2281.     all the fields on the model.
    
  2282. 
    
  2283.     .. note::
    
  2284. 
    
  2285.         :meth:`Options.get_fields()
    
  2286.         <django.db.models.options.Options.get_fields()>`
    
  2287.         excludes hidden fields by default. Pass in ``include_hidden=True`` to
    
  2288.         return hidden fields in the results.
    
  2289. 
    
  2290. .. attribute:: Field.is_relation
    
  2291. 
    
  2292.     Boolean flag that indicates if a field contains references to one or
    
  2293.     more other models for its functionality (e.g. ``ForeignKey``,
    
  2294.     ``ManyToManyField``, ``OneToOneField``, etc.).
    
  2295. 
    
  2296. .. attribute:: Field.model
    
  2297. 
    
  2298.     Returns the model on which the field is defined. If a field is defined on
    
  2299.     a superclass of a model, ``model`` will refer to the superclass, not the
    
  2300.     class of the instance.
    
  2301. 
    
  2302. Attributes for fields with relations
    
  2303. ====================================
    
  2304. 
    
  2305. These attributes are used to query for the cardinality and other details of a
    
  2306. relation. These attribute are present on all fields; however, they will only
    
  2307. have boolean values (rather than ``None``) if the field is a relation type
    
  2308. (:attr:`Field.is_relation=True <Field.is_relation>`).
    
  2309. 
    
  2310. .. attribute:: Field.many_to_many
    
  2311. 
    
  2312.     Boolean flag that is ``True`` if the field has a many-to-many relation;
    
  2313.     ``False`` otherwise. The only field included with Django where this is
    
  2314.     ``True`` is ``ManyToManyField``.
    
  2315. 
    
  2316. .. attribute:: Field.many_to_one
    
  2317. 
    
  2318.     Boolean flag that is ``True`` if the field has a many-to-one relation, such
    
  2319.     as a ``ForeignKey``; ``False`` otherwise.
    
  2320. 
    
  2321. .. attribute:: Field.one_to_many
    
  2322. 
    
  2323.     Boolean flag that is ``True`` if the field has a one-to-many relation, such
    
  2324.     as a ``GenericRelation`` or the reverse of a ``ForeignKey``; ``False``
    
  2325.     otherwise.
    
  2326. 
    
  2327. .. attribute:: Field.one_to_one
    
  2328. 
    
  2329.     Boolean flag that is ``True`` if the field has a one-to-one relation, such
    
  2330.     as a ``OneToOneField``; ``False`` otherwise.
    
  2331. 
    
  2332. .. attribute:: Field.related_model
    
  2333. 
    
  2334.     Points to the model the field relates to. For example, ``Author`` in
    
  2335.     ``ForeignKey(Author, on_delete=models.CASCADE)``. The ``related_model`` for
    
  2336.     a ``GenericForeignKey`` is always ``None``.