Debian Codegraph @

docs/ref/models/fields.txt

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