fields.txt 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884
  1. =====================
  2. Model field reference
  3. =====================
  4. .. module:: django.db.models.fields
  5. :synopsis: Built-in field types.
  6. .. currentmodule:: django.db.models
  7. This document contains all the API references of :class:`Field` including the
  8. `field options`_ and `field types`_ Django offers.
  9. .. seealso::
  10. If the built-in fields don't do the trick, you can try :doc:`localflavor
  11. </topics/localflavor>`, which contains assorted pieces of code
  12. that are useful for particular countries or cultures. Also, you can easily
  13. :doc:`write your own custom model fields </howto/custom-model-fields>`.
  14. .. note::
  15. Technically, these models are defined in :mod:`django.db.models.fields`, but
  16. for convenience they're imported into :mod:`django.db.models`; the standard
  17. convention is to use ``from django.db import models`` and refer to fields as
  18. ``models.<Foo>Field``.
  19. .. _common-model-field-options:
  20. Field options
  21. =============
  22. The following arguments are available to all field types. All are optional.
  23. ``null``
  24. --------
  25. .. attribute:: Field.null
  26. If ``True``, Django will store empty values as ``NULL`` in the database. Default
  27. is ``False``.
  28. Avoid using :attr:`~Field.null` on string-based fields such as
  29. :class:`CharField` and :class:`TextField` because empty string values will
  30. always be stored as empty strings, not as ``NULL``. If a string-based field has
  31. ``null=True``, that means it has two possible values for "no data": ``NULL``,
  32. and the empty string. In most cases, it's redundant to have two possible values
  33. for "no data;" the Django convention is to use the empty string, not ``NULL``.
  34. For both string-based and non-string-based fields, you will also need to
  35. set ``blank=True`` if you wish to permit empty values in forms, as the
  36. :attr:`~Field.null` parameter only affects database storage
  37. (see :attr:`~Field.blank`).
  38. .. note::
  39. When using the Oracle database backend, the value ``NULL`` will be stored to
  40. denote the empty string regardless of this attribute.
  41. If you want to accept :attr:`~Field.null` values with :class:`BooleanField`,
  42. use :class:`NullBooleanField` instead.
  43. ``blank``
  44. ---------
  45. .. attribute:: Field.blank
  46. If ``True``, the field is allowed to be blank. Default is ``False``.
  47. Note that this is different than :attr:`~Field.null`. :attr:`~Field.null` is
  48. purely database-related, whereas :attr:`~Field.blank` is validation-related. If
  49. a field has ``blank=True``, form validation will allow entry of an empty value.
  50. If a field has ``blank=False``, the field will be required.
  51. .. _field-choices:
  52. ``choices``
  53. -----------
  54. .. attribute:: Field.choices
  55. An iterable (e.g., a list or tuple) consisting itself of iterables of exactly
  56. two items (e.g. ``[(A, B), (A, B) ...]``) to use as choices for this field. If
  57. this is given, the default form widget will be a select box with these choices
  58. instead of the standard text field.
  59. The first element in each tuple is the actual value to be set on the model,
  60. and the second element is the human-readable name. For example::
  61. YEAR_IN_SCHOOL_CHOICES = (
  62. ('FR', 'Freshman'),
  63. ('SO', 'Sophomore'),
  64. ('JR', 'Junior'),
  65. ('SR', 'Senior'),
  66. )
  67. Generally, it's best to define choices inside a model class, and to
  68. define a suitably-named constant for each value::
  69. from django.db import models
  70. class Student(models.Model):
  71. FRESHMAN = 'FR'
  72. SOPHOMORE = 'SO'
  73. JUNIOR = 'JR'
  74. SENIOR = 'SR'
  75. YEAR_IN_SCHOOL_CHOICES = (
  76. (FRESHMAN, 'Freshman'),
  77. (SOPHOMORE, 'Sophomore'),
  78. (JUNIOR, 'Junior'),
  79. (SENIOR, 'Senior'),
  80. )
  81. year_in_school = models.CharField(max_length=2,
  82. choices=YEAR_IN_SCHOOL_CHOICES,
  83. default=FRESHMAN)
  84. def is_upperclass(self):
  85. return self.year_in_school in (self.JUNIOR, self.SENIOR)
  86. Though you can define a choices list outside of a model class and then
  87. refer to it, defining the choices and names for each choice inside the
  88. model class keeps all of that information with the class that uses it,
  89. and makes the choices easy to reference (e.g, ``Student.SOPHOMORE``
  90. will work anywhere that the ``Student`` model has been imported).
  91. You can also collect your available choices into named groups that can
  92. be used for organizational purposes::
  93. MEDIA_CHOICES = (
  94. ('Audio', (
  95. ('vinyl', 'Vinyl'),
  96. ('cd', 'CD'),
  97. )
  98. ),
  99. ('Video', (
  100. ('vhs', 'VHS Tape'),
  101. ('dvd', 'DVD'),
  102. )
  103. ),
  104. ('unknown', 'Unknown'),
  105. )
  106. The first element in each tuple is the name to apply to the group. The
  107. second element is an iterable of 2-tuples, with each 2-tuple containing
  108. a value and a human-readable name for an option. Grouped options may be
  109. combined with ungrouped options within a single list (such as the
  110. `unknown` option in this example).
  111. For each model field that has :attr:`~Field.choices` set, Django will add a
  112. method to retrieve the human-readable name for the field's current value. See
  113. :meth:`~django.db.models.Model.get_FOO_display` in the database API
  114. documentation.
  115. Note that choices can be any iterable object -- not necessarily a list or tuple.
  116. This lets you construct choices dynamically. But if you find yourself hacking
  117. :attr:`~Field.choices` to be dynamic, you're probably better off using a proper
  118. database table with a :class:`ForeignKey`. :attr:`~Field.choices` is meant for
  119. static data that doesn't change much, if ever.
  120. .. versionadded:: 1.7
  121. Unless :attr:`blank=False<Field.blank>` is set on the field along with a
  122. :attr:`~Field.default` then a label containing ``"---------"`` will be rendered
  123. with the select box. To override this behavior, add a tuple to ``choices``
  124. containing ``None``; e.g. ``(None, 'Your String For Display')``.
  125. Alternatively, you can use an empty string instead of ``None`` where this makes
  126. sense - such as on a :class:`~django.db.models.CharField`.
  127. ``db_column``
  128. -------------
  129. .. attribute:: Field.db_column
  130. The name of the database column to use for this field. If this isn't given,
  131. Django will use the field's name.
  132. If your database column name is an SQL reserved word, or contains
  133. characters that aren't allowed in Python variable names -- notably, the
  134. hyphen -- that's OK. Django quotes column and table names behind the
  135. scenes.
  136. ``db_index``
  137. ------------
  138. .. attribute:: Field.db_index
  139. If ``True``, :djadmin:`django-admin sqlindexes <sqlindexes>` will output a
  140. ``CREATE INDEX`` statement for this field.
  141. ``db_tablespace``
  142. -----------------
  143. .. attribute:: Field.db_tablespace
  144. The name of the :doc:`database tablespace </topics/db/tablespaces>` to use for
  145. this field's index, if this field is indexed. The default is the project's
  146. :setting:`DEFAULT_INDEX_TABLESPACE` setting, if set, or the
  147. :attr:`~Options.db_tablespace` of the model, if any. If the backend doesn't
  148. support tablespaces for indexes, this option is ignored.
  149. ``default``
  150. -----------
  151. .. attribute:: Field.default
  152. The default value for the field. This can be a value or a callable object. If
  153. callable it will be called every time a new object is created.
  154. The default cannot be a mutable object (model instance, list, set, etc.), as a
  155. reference to the same instance of that object would be used as the default
  156. value in all new model instances. Instead, wrap the desired default in a
  157. callable. For example, if you had a custom ``JSONField`` and wanted to specify
  158. a dictionary as the default, use a function as follows::
  159. def contact_default():
  160. return {"email": "to1@example.com"}
  161. contact_info = JSONField("ContactInfo", default=contact_default)
  162. Note that ``lambda``\s cannot be used for field options like ``default``
  163. because they cannot be :ref:`serialized by migrations <migration-serializing>`.
  164. See that documentation for other caveats.
  165. ``editable``
  166. ------------
  167. .. attribute:: Field.editable
  168. If ``False``, the field will not be displayed in the admin or any other
  169. :class:`~django.forms.ModelForm`. They are also skipped during :ref:`model
  170. validation <validating-objects>`. Default is ``True``.
  171. ``error_messages``
  172. ------------------
  173. .. attribute:: Field.error_messages
  174. The ``error_messages`` argument lets you override the default messages that the
  175. field will raise. Pass in a dictionary with keys matching the error messages you
  176. want to override.
  177. Error message keys include ``null``, ``blank``, ``invalid``, ``invalid_choice``,
  178. ``unique``, and ``unique_for_date``. Additional error message keys are
  179. specified for each field in the `Field types`_ section below.
  180. .. versionadded:: 1.7
  181. The ``unique_for_date`` error message key was added.
  182. ``help_text``
  183. -------------
  184. .. attribute:: Field.help_text
  185. Extra "help" text to be displayed with the form widget. It's useful for
  186. documentation even if your field isn't used on a form.
  187. Note that this value is *not* HTML-escaped in automatically-generated
  188. forms. This lets you include HTML in :attr:`~Field.help_text` if you so
  189. desire. For example::
  190. help_text="Please use the following format: <em>YYYY-MM-DD</em>."
  191. Alternatively you can use plain text and
  192. ``django.utils.html.escape()`` to escape any HTML special characters. Ensure
  193. that you escape any help text that may come from untrusted users to avoid a
  194. cross-site scripting attack.
  195. ``primary_key``
  196. ---------------
  197. .. attribute:: Field.primary_key
  198. If ``True``, this field is the primary key for the model.
  199. If you don't specify ``primary_key=True`` for any field in your model, Django
  200. will automatically add an :class:`AutoField` to hold the primary key, so you
  201. don't need to set ``primary_key=True`` on any of your fields unless you want to
  202. override the default primary-key behavior. For more, see
  203. :ref:`automatic-primary-key-fields`.
  204. ``primary_key=True`` implies :attr:`null=False <Field.null>` and
  205. :attr:`unique=True <Field.unique>`. Only one primary key is allowed on an
  206. object.
  207. The primary key field is read-only. If you change the value of the primary
  208. key on an existing object and then save it, a new object will be created
  209. alongside the old one.
  210. ``unique``
  211. ----------
  212. .. attribute:: Field.unique
  213. If ``True``, this field must be unique throughout the table.
  214. This is enforced at the database level and by model validation. If
  215. you try to save a model with a duplicate value in a :attr:`~Field.unique`
  216. field, a :exc:`django.db.IntegrityError` will be raised by the model's
  217. :meth:`~django.db.models.Model.save` method.
  218. This option is valid on all field types except :class:`ManyToManyField`,
  219. :class:`OneToOneField`, and :class:`FileField`.
  220. Note that when ``unique`` is ``True``, you don't need to specify
  221. :attr:`~Field.db_index`, because ``unique`` implies the creation of an index.
  222. ``unique_for_date``
  223. -------------------
  224. .. attribute:: Field.unique_for_date
  225. Set this to the name of a :class:`DateField` or :class:`DateTimeField` to
  226. require that this field be unique for the value of the date field.
  227. For example, if you have a field ``title`` that has
  228. ``unique_for_date="pub_date"``, then Django wouldn't allow the entry of two
  229. records with the same ``title`` and ``pub_date``.
  230. Note that if you set this to point to a :class:`DateTimeField`, only the date
  231. portion of the field will be considered. Besides, when :setting:`USE_TZ` is
  232. ``True``, the check will be performed in the :ref:`current time zone
  233. <default-current-time-zone>` at the time the object gets saved.
  234. This is enforced by :meth:`Model.validate_unique()` during model validation
  235. but not at the database level. If any :attr:`~Field.unique_for_date` constraint
  236. involves fields that are not part of a :class:`~django.forms.ModelForm` (for
  237. example, if one of the fields is listed in ``exclude`` or has
  238. :attr:`editable=False<Field.editable>`), :meth:`Model.validate_unique()` will
  239. skip validation for that particular constraint.
  240. ``unique_for_month``
  241. --------------------
  242. .. attribute:: Field.unique_for_month
  243. Like :attr:`~Field.unique_for_date`, but requires the field to be unique with
  244. respect to the month.
  245. ``unique_for_year``
  246. -------------------
  247. .. attribute:: Field.unique_for_year
  248. Like :attr:`~Field.unique_for_date` and :attr:`~Field.unique_for_month`.
  249. ``verbose_name``
  250. -------------------
  251. .. attribute:: Field.verbose_name
  252. A human-readable name for the field. If the verbose name isn't given, Django
  253. will automatically create it using the field's attribute name, converting
  254. underscores to spaces. See :ref:`Verbose field names <verbose-field-names>`.
  255. ``validators``
  256. -------------------
  257. .. attribute:: Field.validators
  258. A list of validators to run for this field. See the :doc:`validators
  259. documentation </ref/validators>` for more information.
  260. Registering and fetching lookups
  261. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  262. ``Field`` implements the :ref:`lookup registration API <lookup-registration-api>`.
  263. The API can be used to customize which lookups are available for a field class, and
  264. how lookups are fetched from a field.
  265. .. _model-field-types:
  266. Field types
  267. ===========
  268. .. currentmodule:: django.db.models
  269. ``AutoField``
  270. -------------
  271. .. class:: AutoField(**options)
  272. An :class:`IntegerField` that automatically increments
  273. according to available IDs. You usually won't need to use this directly; a
  274. primary key field will automatically be added to your model if you don't specify
  275. otherwise. See :ref:`automatic-primary-key-fields`.
  276. ``BigIntegerField``
  277. -------------------
  278. .. class:: BigIntegerField([**options])
  279. A 64 bit integer, much like an :class:`IntegerField` except that it is
  280. guaranteed to fit numbers from ``-9223372036854775808`` to
  281. ``9223372036854775807``. The default form widget for this field is a
  282. :class:`~django.forms.TextInput`.
  283. ``BinaryField``
  284. -------------------
  285. .. class:: BinaryField([**options])
  286. A field to store raw binary data. It only supports ``bytes`` assignment. Be
  287. aware that this field has limited functionality. For example, it is not possible
  288. to filter a queryset on a ``BinaryField`` value.
  289. .. admonition:: Abusing ``BinaryField``
  290. Although you might think about storing files in the database, consider that
  291. it is bad design in 99% of the cases. This field is *not* a replacement for
  292. proper :doc:`static files </howto/static-files/index>` handling.
  293. ``BooleanField``
  294. ----------------
  295. .. class:: BooleanField(**options)
  296. A true/false field.
  297. The default form widget for this field is a
  298. :class:`~django.forms.CheckboxInput`.
  299. If you need to accept :attr:`~Field.null` values then use
  300. :class:`NullBooleanField` instead.
  301. The default value of ``BooleanField`` is ``None`` when :attr:`Field.default`
  302. isn't defined.
  303. ``CharField``
  304. -------------
  305. .. class:: CharField(max_length=None, [**options])
  306. A string field, for small- to large-sized strings.
  307. For large amounts of text, use :class:`~django.db.models.TextField`.
  308. The default form widget for this field is a :class:`~django.forms.TextInput`.
  309. :class:`CharField` has one extra required argument:
  310. .. attribute:: CharField.max_length
  311. The maximum length (in characters) of the field. The max_length is enforced
  312. at the database level and in Django's validation.
  313. .. note::
  314. If you are writing an application that must be portable to multiple
  315. database backends, you should be aware that there are restrictions on
  316. ``max_length`` for some backends. Refer to the :doc:`database backend
  317. notes </ref/databases>` for details.
  318. .. admonition:: MySQL users
  319. If you are using this field with MySQLdb 1.2.2 and the ``utf8_bin``
  320. collation (which is *not* the default), there are some issues to be aware
  321. of. Refer to the :ref:`MySQL database notes <mysql-collation>` for
  322. details.
  323. ``CommaSeparatedIntegerField``
  324. ------------------------------
  325. .. class:: CommaSeparatedIntegerField(max_length=None, [**options])
  326. A field of integers separated by commas. As in :class:`CharField`, the
  327. :attr:`~CharField.max_length` argument is required and the note about database
  328. portability mentioned there should be heeded.
  329. ``DateField``
  330. -------------
  331. .. class:: DateField([auto_now=False, auto_now_add=False, **options])
  332. A date, represented in Python by a ``datetime.date`` instance. Has a few extra,
  333. optional arguments:
  334. .. attribute:: DateField.auto_now
  335. Automatically set the field to now every time the object is saved. Useful
  336. for "last-modified" timestamps. Note that the current date is *always*
  337. used; it's not just a default value that you can override.
  338. .. attribute:: DateField.auto_now_add
  339. Automatically set the field to now when the object is first created. Useful
  340. for creation of timestamps. Note that the current date is *always* used;
  341. it's not just a default value that you can override.
  342. The default form widget for this field is a
  343. :class:`~django.forms.TextInput`. The admin adds a JavaScript calendar,
  344. and a shortcut for "Today". Includes an additional ``invalid_date`` error
  345. message key.
  346. The options ``auto_now_add``, ``auto_now``, and ``default`` are mutually exclusive.
  347. Any combination of these options will result in an error.
  348. .. note::
  349. As currently implemented, setting ``auto_now`` or ``auto_now_add`` to
  350. ``True`` will cause the field to have ``editable=False`` and ``blank=True``
  351. set.
  352. ``DateTimeField``
  353. -----------------
  354. .. class:: DateTimeField([auto_now=False, auto_now_add=False, **options])
  355. A date and time, represented in Python by a ``datetime.datetime`` instance.
  356. Takes the same extra arguments as :class:`DateField`.
  357. The default form widget for this field is a single
  358. :class:`~django.forms.TextInput`. The admin uses two separate
  359. :class:`~django.forms.TextInput` widgets with JavaScript shortcuts.
  360. ``DecimalField``
  361. ----------------
  362. .. class:: DecimalField(max_digits=None, decimal_places=None, [**options])
  363. A fixed-precision decimal number, represented in Python by a
  364. :class:`~decimal.Decimal` instance. Has two **required** arguments:
  365. .. attribute:: DecimalField.max_digits
  366. The maximum number of digits allowed in the number. Note that this number
  367. must be greater than or equal to ``decimal_places``.
  368. .. attribute:: DecimalField.decimal_places
  369. The number of decimal places to store with the number.
  370. For example, to store numbers up to ``999`` with a resolution of 2 decimal
  371. places, you'd use::
  372. models.DecimalField(..., max_digits=5, decimal_places=2)
  373. And to store numbers up to approximately one billion with a resolution of 10
  374. decimal places::
  375. models.DecimalField(..., max_digits=19, decimal_places=10)
  376. The default form widget for this field is a :class:`~django.forms.TextInput`.
  377. .. note::
  378. For more information about the differences between the
  379. :class:`FloatField` and :class:`DecimalField` classes, please
  380. see :ref:`FloatField vs. DecimalField <floatfield_vs_decimalfield>`.
  381. ``DurationField``
  382. -----------------
  383. .. versionadded:: 1.8
  384. .. class:: DurationField([**options])
  385. A field for storing periods of time - modeled in Python by
  386. :class:`~python:datetime.timedelta`. When used on PostgreSQL, the data type
  387. used is an ``interval`` and on Oracle the data type is ``INTERVAL DAY(9) TO
  388. SECOND(6)``. Otherwise a ``bigint`` of microseconds is used.
  389. .. note::
  390. Arithmetic with ``DurationField`` works in most cases. However on all
  391. databases other than PostgreSQL, comparing the value of a ``DurationField``
  392. to arithmetic on ``DateTimeField`` instances will not work as expected.
  393. ``EmailField``
  394. --------------
  395. .. class:: EmailField([max_length=254, **options])
  396. A :class:`CharField` that checks that the value is a valid email address. It
  397. uses :class:`~django.core.validators.EmailValidator` to validate the input.
  398. .. versionchanged:: 1.8
  399. The default ``max_length`` was increased from 75 to 254 in order to be
  400. compliant with RFC3696/5321.
  401. ``FileField``
  402. -------------
  403. .. class:: FileField([upload_to=None, max_length=100, **options])
  404. A file-upload field.
  405. .. note::
  406. The ``primary_key`` and ``unique`` arguments are not supported, and will
  407. raise a ``TypeError`` if used.
  408. Has two optional arguments:
  409. .. attribute:: FileField.upload_to
  410. .. versionchanged:: 1.7
  411. ``upload_to`` was required in older versions of Django.
  412. A local filesystem path that will be appended to your :setting:`MEDIA_ROOT`
  413. setting to determine the value of the
  414. :attr:`~django.db.models.fields.files.FieldFile.url` attribute.
  415. This path may contain :func:`~time.strftime` formatting, which will be
  416. replaced by the date/time of the file upload (so that uploaded files don't
  417. fill up the given directory).
  418. This may also be a callable, such as a function, which will be called to
  419. obtain the upload path, including the filename. This callable must be able
  420. to accept two arguments, and return a Unix-style path (with forward slashes)
  421. to be passed along to the storage system. The two arguments that will be
  422. passed are:
  423. ====================== ===============================================
  424. Argument Description
  425. ====================== ===============================================
  426. ``instance`` An instance of the model where the
  427. ``FileField`` is defined. More specifically,
  428. this is the particular instance where the
  429. current file is being attached.
  430. In most cases, this object will not have been
  431. saved to the database yet, so if it uses the
  432. default ``AutoField``, *it might not yet have a
  433. value for its primary key field*.
  434. ``filename`` The filename that was originally given to the
  435. file. This may or may not be taken into account
  436. when determining the final destination path.
  437. ====================== ===============================================
  438. .. attribute:: FileField.storage
  439. A storage object, which handles the storage and retrieval of your
  440. files. See :doc:`/topics/files` for details on how to provide this object.
  441. The default form widget for this field is a
  442. :class:`~django.forms.ClearableFileInput`.
  443. Using a :class:`FileField` or an :class:`ImageField` (see below) in a model
  444. takes a few steps:
  445. 1. In your settings file, you'll need to define :setting:`MEDIA_ROOT` as the
  446. full path to a directory where you'd like Django to store uploaded files.
  447. (For performance, these files are not stored in the database.) Define
  448. :setting:`MEDIA_URL` as the base public URL of that directory. Make sure
  449. that this directory is writable by the Web server's user account.
  450. 2. Add the :class:`FileField` or :class:`ImageField` to your model, defining
  451. the :attr:`~FileField.upload_to` option to specify a subdirectory of
  452. :setting:`MEDIA_ROOT` to use for uploaded files.
  453. 3. All that will be stored in your database is a path to the file
  454. (relative to :setting:`MEDIA_ROOT`). You'll most likely want to use the
  455. convenience :attr:`~django.db.models.fields.files.FieldFile.url` attribute
  456. provided by Django. For example, if your :class:`ImageField` is called
  457. ``mug_shot``, you can get the absolute path to your image in a template with
  458. ``{{ object.mug_shot.url }}``.
  459. For example, say your :setting:`MEDIA_ROOT` is set to ``'/home/media'``, and
  460. :attr:`~FileField.upload_to` is set to ``'photos/%Y/%m/%d'``. The ``'%Y/%m/%d'``
  461. part of :attr:`~FileField.upload_to` is :func:`~time.strftime` formatting;
  462. ``'%Y'`` is the four-digit year, ``'%m'`` is the two-digit month and ``'%d'`` is
  463. the two-digit day. If you upload a file on Jan. 15, 2007, it will be saved in
  464. the directory ``/home/media/photos/2007/01/15``.
  465. If you wanted to retrieve the uploaded file's on-disk filename, or the file's
  466. size, you could use the :attr:`~django.core.files.File.name` and
  467. :attr:`~django.core.files.File.size` attributes respectively; for more
  468. information on the available attributes and methods, see the
  469. :class:`~django.core.files.File` class reference and the :doc:`/topics/files`
  470. topic guide.
  471. .. note::
  472. The file is saved as part of saving the model in the database, so the actual
  473. file name used on disk cannot be relied on until after the model has been
  474. saved.
  475. The uploaded file's relative URL can be obtained using the
  476. :attr:`~django.db.models.fields.files.FieldFile.url` attribute. Internally,
  477. this calls the :meth:`~django.core.files.storage.Storage.url` method of the
  478. underlying :class:`~django.core.files.storage.Storage` class.
  479. .. _file-upload-security:
  480. Note that whenever you deal with uploaded files, you should pay close attention
  481. to where you're uploading them and what type of files they are, to avoid
  482. security holes. *Validate all uploaded files* so that you're sure the files are
  483. what you think they are. For example, if you blindly let somebody upload files,
  484. without validation, to a directory that's within your Web server's document
  485. root, then somebody could upload a CGI or PHP script and execute that script by
  486. visiting its URL on your site. Don't allow that.
  487. Also note that even an uploaded HTML file, since it can be executed by the
  488. browser (though not by the server), can pose security threats that are
  489. equivalent to XSS or CSRF attacks.
  490. :class:`FileField` instances are created in your database as ``varchar``
  491. columns with a default max length of 100 characters. As with other fields, you
  492. can change the maximum length using the :attr:`~CharField.max_length` argument.
  493. FileField and FieldFile
  494. ~~~~~~~~~~~~~~~~~~~~~~~
  495. .. currentmodule:: django.db.models.fields.files
  496. .. class:: FieldFile
  497. When you access a :class:`~django.db.models.FileField` on a model, you are
  498. given an instance of :class:`FieldFile` as a proxy for accessing the underlying
  499. file. In addition to the functionality inherited from
  500. :class:`django.core.files.File`, this class has several attributes and methods
  501. that can be used to interact with file data:
  502. .. attribute:: FieldFile.url
  503. A read-only property to access the file's relative URL by calling the
  504. :meth:`~django.core.files.storage.Storage.url` method of the underlying
  505. :class:`~django.core.files.storage.Storage` class.
  506. .. method:: FieldFile.open(mode='rb')
  507. Behaves like the standard Python ``open()`` method and opens the file
  508. associated with this instance in the mode specified by ``mode``.
  509. .. method:: FieldFile.close()
  510. Behaves like the standard Python ``file.close()`` method and closes the file
  511. associated with this instance.
  512. .. method:: FieldFile.save(name, content, save=True)
  513. This method takes a filename and file contents and passes them to the storage
  514. class for the field, then associates the stored file with the model field.
  515. If you want to manually associate file data with
  516. :class:`~django.db.models.FileField` instances on your model, the ``save()``
  517. method is used to persist that file data.
  518. Takes two required arguments: ``name`` which is the name of the file, and
  519. ``content`` which is an object containing the file's contents. The
  520. optional ``save`` argument controls whether or not the model instance is
  521. saved after the file associated with this field has been altered. Defaults to
  522. ``True``.
  523. Note that the ``content`` argument should be an instance of
  524. :class:`django.core.files.File`, not Python's built-in file object.
  525. You can construct a :class:`~django.core.files.File` from an existing
  526. Python file object like this::
  527. from django.core.files import File
  528. # Open an existing file using Python's built-in open()
  529. f = open('/tmp/hello.world')
  530. myfile = File(f)
  531. Or you can construct one from a Python string like this::
  532. from django.core.files.base import ContentFile
  533. myfile = ContentFile("hello world")
  534. For more information, see :doc:`/topics/files`.
  535. .. method:: FieldFile.delete(save=True)
  536. Deletes the file associated with this instance and clears all attributes on
  537. the field. Note: This method will close the file if it happens to be open when
  538. ``delete()`` is called.
  539. The optional ``save`` argument controls whether or not the model instance is
  540. saved after the file associated with this field has been deleted. Defaults to
  541. ``True``.
  542. Note that when a model is deleted, related files are not deleted. If you need
  543. to cleanup orphaned files, you'll need to handle it yourself (for instance,
  544. with a custom management command that can be run manually or scheduled to run
  545. periodically via e.g. cron).
  546. .. currentmodule:: django.db.models
  547. ``FilePathField``
  548. -----------------
  549. .. class:: FilePathField(path=None, [match=None, recursive=False, max_length=100, **options])
  550. A :class:`CharField` whose choices are limited to the filenames in a certain
  551. directory on the filesystem. Has three special arguments, of which the first is
  552. **required**:
  553. .. attribute:: FilePathField.path
  554. Required. The absolute filesystem path to a directory from which this
  555. :class:`FilePathField` should get its choices. Example: ``"/home/images"``.
  556. .. attribute:: FilePathField.match
  557. Optional. A regular expression, as a string, that :class:`FilePathField`
  558. will use to filter filenames. Note that the regex will be applied to the
  559. base filename, not the full path. Example: ``"foo.*\.txt$"``, which will
  560. match a file called ``foo23.txt`` but not ``bar.txt`` or ``foo23.png``.
  561. .. attribute:: FilePathField.recursive
  562. Optional. Either ``True`` or ``False``. Default is ``False``. Specifies
  563. whether all subdirectories of :attr:`~FilePathField.path` should be included
  564. .. attribute:: FilePathField.allow_files
  565. Optional. Either ``True`` or ``False``. Default is ``True``. Specifies
  566. whether files in the specified location should be included. Either this or
  567. :attr:`~FilePathField.allow_folders` must be ``True``.
  568. .. attribute:: FilePathField.allow_folders
  569. Optional. Either ``True`` or ``False``. Default is ``False``. Specifies
  570. whether folders in the specified location should be included. Either this
  571. or :attr:`~FilePathField.allow_files` must be ``True``.
  572. Of course, these arguments can be used together.
  573. The one potential gotcha is that :attr:`~FilePathField.match` applies to the
  574. base filename, not the full path. So, this example::
  575. FilePathField(path="/home/images", match="foo.*", recursive=True)
  576. ...will match ``/home/images/foo.png`` but not ``/home/images/foo/bar.png``
  577. because the :attr:`~FilePathField.match` applies to the base filename
  578. (``foo.png`` and ``bar.png``).
  579. :class:`FilePathField` instances are created in your database as ``varchar``
  580. columns with a default max length of 100 characters. As with other fields, you
  581. can change the maximum length using the :attr:`~CharField.max_length` argument.
  582. ``FloatField``
  583. --------------
  584. .. class:: FloatField([**options])
  585. A floating-point number represented in Python by a ``float`` instance.
  586. The default form widget for this field is a :class:`~django.forms.TextInput`.
  587. .. _floatfield_vs_decimalfield:
  588. .. admonition:: ``FloatField`` vs. ``DecimalField``
  589. The :class:`FloatField` class is sometimes mixed up with the
  590. :class:`DecimalField` class. Although they both represent real numbers, they
  591. represent those numbers differently. ``FloatField`` uses Python's ``float``
  592. type internally, while ``DecimalField`` uses Python's ``Decimal`` type. For
  593. information on the difference between the two, see Python's documentation
  594. for the :mod:`decimal` module.
  595. ``ImageField``
  596. --------------
  597. .. class:: ImageField([upload_to=None, height_field=None, width_field=None, max_length=100, **options])
  598. Inherits all attributes and methods from :class:`FileField`, but also
  599. validates that the uploaded object is a valid image.
  600. In addition to the special attributes that are available for :class:`FileField`,
  601. an :class:`ImageField` also has ``height`` and ``width`` attributes.
  602. To facilitate querying on those attributes, :class:`ImageField` has two extra
  603. optional arguments:
  604. .. attribute:: ImageField.height_field
  605. Name of a model field which will be auto-populated with the height of the
  606. image each time the model instance is saved.
  607. .. attribute:: ImageField.width_field
  608. Name of a model field which will be auto-populated with the width of the
  609. image each time the model instance is saved.
  610. Requires the `Pillow`_ library.
  611. .. _Pillow: http://pillow.readthedocs.org/en/latest/
  612. :class:`ImageField` instances are created in your database as ``varchar``
  613. columns with a default max length of 100 characters. As with other fields, you
  614. can change the maximum length using the :attr:`~CharField.max_length` argument.
  615. The default form widget for this field is a
  616. :class:`~django.forms.ClearableFileInput`.
  617. ``IntegerField``
  618. ----------------
  619. .. class:: IntegerField([**options])
  620. An integer. Values from ``-2147483648`` to ``2147483647`` are safe in all
  621. databases supported by Django. The default form widget for this field is a
  622. :class:`~django.forms.TextInput`.
  623. ``IPAddressField``
  624. ------------------
  625. .. class:: IPAddressField([**options])
  626. .. deprecated:: 1.7
  627. This field has been deprecated in favor of
  628. :class:`~django.db.models.GenericIPAddressField`.
  629. An IP address, in string format (e.g. "192.0.2.30"). The default form widget
  630. for this field is a :class:`~django.forms.TextInput`.
  631. ``GenericIPAddressField``
  632. -------------------------
  633. .. class:: GenericIPAddressField([protocol=both, unpack_ipv4=False, **options])
  634. An IPv4 or IPv6 address, in string format (e.g. ``192.0.2.30`` or
  635. ``2a02:42fe::4``). The default form widget for this field is a
  636. :class:`~django.forms.TextInput`.
  637. The IPv6 address normalization follows :rfc:`4291#section-2.2` section 2.2,
  638. including using the IPv4 format suggested in paragraph 3 of that section, like
  639. ``::ffff:192.0.2.0``. For example, ``2001:0::0:01`` would be normalized to
  640. ``2001::1``, and ``::ffff:0a0a:0a0a`` to ``::ffff:10.10.10.10``. All characters
  641. are converted to lowercase.
  642. .. attribute:: GenericIPAddressField.protocol
  643. Limits valid inputs to the specified protocol.
  644. Accepted values are ``'both'`` (default), ``'IPv4'``
  645. or ``'IPv6'``. Matching is case insensitive.
  646. .. attribute:: GenericIPAddressField.unpack_ipv4
  647. Unpacks IPv4 mapped addresses like ``::ffff:192.0.2.1``.
  648. If this option is enabled that address would be unpacked to
  649. ``192.0.2.1``. Default is disabled. Can only be used
  650. when ``protocol`` is set to ``'both'``.
  651. If you allow for blank values, you have to allow for null values since blank
  652. values are stored as null.
  653. ``NullBooleanField``
  654. --------------------
  655. .. class:: NullBooleanField([**options])
  656. Like a :class:`BooleanField`, but allows ``NULL`` as one of the options. Use
  657. this instead of a :class:`BooleanField` with ``null=True``. The default form
  658. widget for this field is a :class:`~django.forms.NullBooleanSelect`.
  659. ``PositiveIntegerField``
  660. ------------------------
  661. .. class:: PositiveIntegerField([**options])
  662. Like an :class:`IntegerField`, but must be either positive or zero (``0``).
  663. Values from ``0`` to ``2147483647`` are safe in all databases supported by
  664. Django. The value ``0`` is accepted for backward compatibility reasons.
  665. ``PositiveSmallIntegerField``
  666. -----------------------------
  667. .. class:: PositiveSmallIntegerField([**options])
  668. Like a :class:`PositiveIntegerField`, but only allows values under a certain
  669. (database-dependent) point. Values from ``0`` to ``32767`` are safe in all
  670. databases supported by Django.
  671. ``SlugField``
  672. -------------
  673. .. class:: SlugField([max_length=50, **options])
  674. :term:`Slug` is a newspaper term. A slug is a short label for something,
  675. containing only letters, numbers, underscores or hyphens. They're generally used
  676. in URLs.
  677. Like a CharField, you can specify :attr:`~CharField.max_length` (read the note
  678. about database portability and :attr:`~CharField.max_length` in that section,
  679. too). If :attr:`~CharField.max_length` is not specified, Django will use a
  680. default length of 50.
  681. Implies setting :attr:`Field.db_index` to ``True``.
  682. It is often useful to automatically prepopulate a SlugField based on the value
  683. of some other value. You can do this automatically in the admin using
  684. :attr:`~django.contrib.admin.ModelAdmin.prepopulated_fields`.
  685. ``SmallIntegerField``
  686. ---------------------
  687. .. class:: SmallIntegerField([**options])
  688. Like an :class:`IntegerField`, but only allows values under a certain
  689. (database-dependent) point. Values from ``-32768`` to ``32767`` are safe in all
  690. databases supported by Django.
  691. ``TextField``
  692. -------------
  693. .. class:: TextField([**options])
  694. A large text field. The default form widget for this field is a
  695. :class:`~django.forms.Textarea`.
  696. .. versionchanged:: 1.7
  697. If you specify a ``max_length`` attribute, it will be reflected in the
  698. :class:`~django.forms.Textarea` widget of the auto-generated form field.
  699. However it is not enforced at the model or database level. Use a
  700. :class:`CharField` for that.
  701. .. admonition:: MySQL users
  702. If you are using this field with MySQLdb 1.2.1p2 and the ``utf8_bin``
  703. collation (which is *not* the default), there are some issues to be aware
  704. of. Refer to the :ref:`MySQL database notes <mysql-collation>` for
  705. details.
  706. ``TimeField``
  707. -------------
  708. .. class:: TimeField([auto_now=False, auto_now_add=False, **options])
  709. A time, represented in Python by a ``datetime.time`` instance. Accepts the same
  710. auto-population options as :class:`DateField`.
  711. The default form widget for this field is a :class:`~django.forms.TextInput`.
  712. The admin adds some JavaScript shortcuts.
  713. ``URLField``
  714. ------------
  715. .. class:: URLField([max_length=200, **options])
  716. A :class:`CharField` for a URL.
  717. The default form widget for this field is a :class:`~django.forms.TextInput`.
  718. Like all :class:`CharField` subclasses, :class:`URLField` takes the optional
  719. :attr:`~CharField.max_length` argument. If you don't specify
  720. :attr:`~CharField.max_length`, a default of 200 is used.
  721. ``UUIDField``
  722. -------------
  723. .. versionadded:: 1.8
  724. .. class:: UUIDField([**options])
  725. A field for storing universally unique identifiers. Uses Python's
  726. :class:`~python:uuid.UUID` class. When used on PostgreSQL, this stores in a
  727. ``uuid`` datatype, otherwise in a ``char(32)``.
  728. Universally unique identifiers are a good alternative to :class:`AutoField` for
  729. :attr:`~Field.primary_key`. The database will not generate the UUID for you, so
  730. it is recommended to use :attr:`~Field.default`::
  731. import uuid
  732. from django.db import models
  733. class MyUUIDModel(models.Model):
  734. id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
  735. # other fields
  736. Note that a callable (with the parentheses omitted) is passed to ``default``,
  737. not an instance of ``UUID``.
  738. Relationship fields
  739. ===================
  740. .. module:: django.db.models.fields.related
  741. :synopsis: Related field types
  742. .. currentmodule:: django.db.models
  743. Django also defines a set of fields that represent relations.
  744. .. _ref-foreignkey:
  745. ``ForeignKey``
  746. --------------
  747. .. class:: ForeignKey(othermodel, [**options])
  748. A many-to-one relationship. Requires a positional argument: the class to which
  749. the model is related.
  750. .. _recursive-relationships:
  751. To create a recursive relationship -- an object that has a many-to-one
  752. relationship with itself -- use ``models.ForeignKey('self')``.
  753. .. _lazy-relationships:
  754. If you need to create a relationship on a model that has not yet been defined,
  755. you can use the name of the model, rather than the model object itself::
  756. from django.db import models
  757. class Car(models.Model):
  758. manufacturer = models.ForeignKey('Manufacturer')
  759. # ...
  760. class Manufacturer(models.Model):
  761. # ...
  762. pass
  763. To refer to models defined in another application, you can explicitly specify
  764. a model with the full application label. For example, if the ``Manufacturer``
  765. model above is defined in another application called ``production``, you'd
  766. need to use::
  767. class Car(models.Model):
  768. manufacturer = models.ForeignKey('production.Manufacturer')
  769. This sort of reference can be useful when resolving circular import
  770. dependencies between two applications.
  771. A database index is automatically created on the ``ForeignKey``. You can
  772. disable this by setting :attr:`~Field.db_index` to ``False``. You may want to
  773. avoid the overhead of an index if you are creating a foreign key for
  774. consistency rather than joins, or if you will be creating an alternative index
  775. like a partial or multiple column index.
  776. .. warning::
  777. It is not recommended to have a ``ForeignKey`` from an app without migrations
  778. to an app with migrations. See the :ref:`dependencies documentation
  779. <unmigrated-dependencies>` for more details.
  780. Database Representation
  781. ~~~~~~~~~~~~~~~~~~~~~~~
  782. Behind the scenes, Django appends ``"_id"`` to the field name to create its
  783. database column name. In the above example, the database table for the ``Car``
  784. model will have a ``manufacturer_id`` column. (You can change this explicitly by
  785. specifying :attr:`~Field.db_column`) However, your code should never have to
  786. deal with the database column name, unless you write custom SQL. You'll always
  787. deal with the field names of your model object.
  788. .. _foreign-key-arguments:
  789. Arguments
  790. ~~~~~~~~~
  791. :class:`ForeignKey` accepts an extra set of arguments -- all optional -- that
  792. define the details of how the relation works.
  793. .. attribute:: ForeignKey.limit_choices_to
  794. Sets a limit to the available choices for this field when this field is
  795. rendered using a ``ModelForm`` or the admin (by default, all objects
  796. in the queryset are available to choose). Either a dictionary, a
  797. :class:`~django.db.models.Q` object, or a callable returning a
  798. dictionary or :class:`~django.db.models.Q` object can be used.
  799. For example::
  800. staff_member = models.ForeignKey(User, limit_choices_to={'is_staff': True})
  801. causes the corresponding field on the ``ModelForm`` to list only ``Users``
  802. that have ``is_staff=True``. This may be helpful in the Django admin.
  803. The callable form can be helpful, for instance, when used in conjunction
  804. with the Python ``datetime`` module to limit selections by date range. For
  805. example::
  806. def limit_pub_date_choices():
  807. return {'pub_date__lte': datetime.date.utcnow()}
  808. limit_choices_to = limit_pub_date_choices
  809. If ``limit_choices_to`` is or returns a :class:`Q object
  810. <django.db.models.Q>`, which is useful for :ref:`complex queries
  811. <complex-lookups-with-q>`, then it will only have an effect on the choices
  812. available in the admin when the field is not listed in
  813. :attr:`~django.contrib.admin.ModelAdmin.raw_id_fields` in the
  814. ``ModelAdmin`` for the model.
  815. .. versionchanged:: 1.7
  816. Previous versions of Django do not allow passing a callable as a value
  817. for ``limit_choices_to``.
  818. .. note::
  819. If a callable is used for ``limit_choices_to``, it will be invoked
  820. every time a new form is instantiated. It may also be invoked when a
  821. model is validated, for example by management commands or the admin.
  822. The admin constructs querysets to validate its form inputs in various
  823. edge cases multiple times, so there is a possibility your callable may
  824. be invoked several times.
  825. .. attribute:: ForeignKey.related_name
  826. The name to use for the relation from the related object back to this one.
  827. It's also the default value for :attr:`related_query_name` (the name to use
  828. for the reverse filter name from the target model). See the :ref:`related
  829. objects documentation <backwards-related-objects>` for a full explanation
  830. and example. Note that you must set this value when defining relations on
  831. :ref:`abstract models <abstract-base-classes>`; and when you do so
  832. :ref:`some special syntax <abstract-related-name>` is available.
  833. If you'd prefer Django not to create a backwards relation, set
  834. ``related_name`` to ``'+'`` or end it with ``'+'``. For example, this will
  835. ensure that the ``User`` model won't have a backwards relation to this
  836. model::
  837. user = models.ForeignKey(User, related_name='+')
  838. .. attribute:: ForeignKey.related_query_name
  839. The name to use for the reverse filter name from the target model.
  840. Defaults to the value of :attr:`related_name` if it is set, otherwise it
  841. defaults to the name of the model::
  842. # Declare the ForeignKey with related_query_name
  843. class Tag(models.Model):
  844. article = models.ForeignKey(Article, related_name="tags", related_query_name="tag")
  845. name = models.CharField(max_length=255)
  846. # That's now the name of the reverse filter
  847. Article.objects.filter(tag__name="important")
  848. .. attribute:: ForeignKey.to_field
  849. The field on the related object that the relation is to. By default, Django
  850. uses the primary key of the related object.
  851. .. attribute:: ForeignKey.db_constraint
  852. Controls whether or not a constraint should be created in the database for
  853. this foreign key. The default is ``True``, and that's almost certainly what
  854. you want; setting this to ``False`` can be very bad for data integrity.
  855. That said, here are some scenarios where you might want to do this:
  856. * You have legacy data that is not valid.
  857. * You're sharding your database.
  858. If this is set to ``False``, accessing a related object that doesn't exist
  859. will raise its ``DoesNotExist`` exception.
  860. .. attribute:: ForeignKey.on_delete
  861. When an object referenced by a :class:`ForeignKey` is deleted, Django by
  862. default emulates the behavior of the SQL constraint ``ON DELETE CASCADE``
  863. and also deletes the object containing the ``ForeignKey``. This behavior
  864. can be overridden by specifying the :attr:`on_delete` argument. For
  865. example, if you have a nullable :class:`ForeignKey` and you want it to be
  866. set null when the referenced object is deleted::
  867. user = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL)
  868. The possible values for :attr:`~ForeignKey.on_delete` are found in
  869. :mod:`django.db.models`:
  870. * .. attribute:: CASCADE
  871. Cascade deletes; the default.
  872. * .. attribute:: PROTECT
  873. Prevent deletion of the referenced object by raising
  874. :exc:`~django.db.models.ProtectedError`, a subclass of
  875. :exc:`django.db.IntegrityError`.
  876. * .. attribute:: SET_NULL
  877. Set the :class:`ForeignKey` null; this is only possible if
  878. :attr:`~Field.null` is ``True``.
  879. * .. attribute:: SET_DEFAULT
  880. Set the :class:`ForeignKey` to its default value; a default for the
  881. :class:`ForeignKey` must be set.
  882. * .. function:: SET()
  883. Set the :class:`ForeignKey` to the value passed to
  884. :func:`~django.db.models.SET()`, or if a callable is passed in,
  885. the result of calling it. In most cases, passing a callable will be
  886. necessary to avoid executing queries at the time your models.py is
  887. imported::
  888. from django.conf import settings
  889. from django.contrib.auth import get_user_model
  890. from django.db import models
  891. def get_sentinel_user():
  892. return get_user_model().objects.get_or_create(username='deleted')[0]
  893. class MyModel(models.Model):
  894. user = models.ForeignKey(settings.AUTH_USER_MODEL,
  895. on_delete=models.SET(get_sentinel_user))
  896. * .. attribute:: DO_NOTHING
  897. Take no action. If your database backend enforces referential
  898. integrity, this will cause an :exc:`~django.db.IntegrityError` unless
  899. you manually add an SQL ``ON DELETE`` constraint to the database field
  900. (perhaps using :ref:`initial sql<initial-sql>`).
  901. .. attribute:: ForeignKey.swappable
  902. .. versionadded:: 1.7
  903. Controls the migration framework's reaction if this :class:`ForeignKey`
  904. is pointing at a swappable model. If it is ``True`` - the default -
  905. then if the :class:`ForeignKey` is pointing at a model which matches
  906. the current value of ``settings.AUTH_USER_MODEL`` (or another swappable
  907. model setting) the relationship will be stored in the migration using
  908. a reference to the setting, not to the model directly.
  909. You only want to override this to be ``False`` if you are sure your
  910. model should always point towards the swapped-in model - for example,
  911. if it is a profile model designed specifically for your custom user model.
  912. Setting it to ``False`` does not mean you can reference a swappable model
  913. even if it is swapped out - ``False`` just means that the migrations made
  914. with this ForeignKey will always reference the exact model you specify
  915. (so it will fail hard if the user tries to run with a User model you don't
  916. support, for example).
  917. If in doubt, leave it to its default of ``True``.
  918. .. _ref-manytomany:
  919. ``ManyToManyField``
  920. -------------------
  921. .. class:: ManyToManyField(othermodel, [**options])
  922. A many-to-many relationship. Requires a positional argument: the class to
  923. which the model is related, which works exactly the same as it does for
  924. :class:`ForeignKey`, including :ref:`recursive <recursive-relationships>` and
  925. :ref:`lazy <lazy-relationships>` relationships.
  926. Related objects can be added, removed, or created with the field's
  927. :class:`~django.db.models.fields.related.RelatedManager`.
  928. .. warning::
  929. It is not recommended to have a ``ManyToManyField`` from an app without migrations
  930. to an app with migrations. See the :ref:`dependencies documentation
  931. <unmigrated-dependencies>` for more details.
  932. Database Representation
  933. ~~~~~~~~~~~~~~~~~~~~~~~
  934. Behind the scenes, Django creates an intermediary join table to represent the
  935. many-to-many relationship. By default, this table name is generated using the
  936. name of the many-to-many field and the name of the table for the model that
  937. contains it. Since some databases don't support table names above a certain
  938. length, these table names will be automatically truncated to 64 characters and a
  939. uniqueness hash will be used. This means you might see table names like
  940. ``author_books_9cdf4``; this is perfectly normal. You can manually provide the
  941. name of the join table using the :attr:`~ManyToManyField.db_table` option.
  942. .. _manytomany-arguments:
  943. Arguments
  944. ~~~~~~~~~
  945. :class:`ManyToManyField` accepts an extra set of arguments -- all optional --
  946. that control how the relationship functions.
  947. .. attribute:: ManyToManyField.related_name
  948. Same as :attr:`ForeignKey.related_name`.
  949. .. attribute:: ManyToManyField.related_query_name
  950. Same as :attr:`ForeignKey.related_query_name`.
  951. .. attribute:: ManyToManyField.limit_choices_to
  952. Same as :attr:`ForeignKey.limit_choices_to`.
  953. ``limit_choices_to`` has no effect when used on a ``ManyToManyField`` with a
  954. custom intermediate table specified using the
  955. :attr:`~ManyToManyField.through` parameter.
  956. .. attribute:: ManyToManyField.symmetrical
  957. Only used in the definition of ManyToManyFields on self. Consider the
  958. following model::
  959. from django.db import models
  960. class Person(models.Model):
  961. friends = models.ManyToManyField("self")
  962. When Django processes this model, it identifies that it has a
  963. :class:`ManyToManyField` on itself, and as a result, it doesn't add a
  964. ``person_set`` attribute to the ``Person`` class. Instead, the
  965. :class:`ManyToManyField` is assumed to be symmetrical -- that is, if I am
  966. your friend, then you are my friend.
  967. If you do not want symmetry in many-to-many relationships with ``self``, set
  968. :attr:`~ManyToManyField.symmetrical` to ``False``. This will force Django to
  969. add the descriptor for the reverse relationship, allowing
  970. :class:`ManyToManyField` relationships to be non-symmetrical.
  971. .. attribute:: ManyToManyField.through
  972. Django will automatically generate a table to manage many-to-many
  973. relationships. However, if you want to manually specify the intermediary
  974. table, you can use the :attr:`~ManyToManyField.through` option to specify
  975. the Django model that represents the intermediate table that you want to
  976. use.
  977. The most common use for this option is when you want to associate
  978. :ref:`extra data with a many-to-many relationship
  979. <intermediary-manytomany>`.
  980. If you don't specify an explicit ``through`` model, there is still an
  981. implicit ``through`` model class you can use to directly access the table
  982. created to hold the association. It has three fields:
  983. * ``id``: the primary key of the relation.
  984. * ``<containing_model>_id``: the ``id`` of the model that declares the
  985. ``ManyToManyField``.
  986. * ``<other_model>_id``: the ``id`` of the model that the
  987. ``ManyToManyField`` points to.
  988. This class can be used to query associated records for a given model
  989. instance like a normal model.
  990. .. attribute:: ManyToManyField.through_fields
  991. .. versionadded:: 1.7
  992. Only used when a custom intermediary model is specified. Django will
  993. normally determine which fields of the intermediary model to use in order
  994. to establish a many-to-many relationship automatically. However,
  995. consider the following models::
  996. from django.db import models
  997. class Person(models.Model):
  998. name = models.CharField(max_length=50)
  999. class Group(models.Model):
  1000. name = models.CharField(max_length=128)
  1001. members = models.ManyToManyField(Person, through='Membership', through_fields=('group', 'person'))
  1002. class Membership(models.Model):
  1003. group = models.ForeignKey(Group)
  1004. person = models.ForeignKey(Person)
  1005. inviter = models.ForeignKey(Person, related_name="membership_invites")
  1006. invite_reason = models.CharField(max_length=64)
  1007. ``Membership`` has *two* foreign keys to ``Person`` (``person`` and
  1008. ``inviter``), which makes the relationship ambiguous and Django can't know
  1009. which one to use. In this case, you must explicitly specify which
  1010. foreign keys Django should use using ``through_fields``, as in the example
  1011. above.
  1012. ``through_fields`` accepts a 2-tuple ``('field1', 'field2')``, where
  1013. ``field1`` is the name of the foreign key to the model the
  1014. :class:`ManyToManyField` is defined on (``group`` in this case), and
  1015. ``field2`` the name of the foreign key to the target model (``person``
  1016. in this case).
  1017. When you have more than one foreign key on an intermediary model to any
  1018. (or even both) of the models participating in a many-to-many relationship,
  1019. you *must* specify ``through_fields``. This also applies to
  1020. :ref:`recursive relationships <recursive-relationships>`
  1021. when an intermediary model is used and there are more than two
  1022. foreign keys to the model, or you want to explicitly specify which two
  1023. Django should use.
  1024. Recursive relationships using an intermediary model are always defined as
  1025. non-symmetrical -- that is, with :attr:`symmetrical=False <ManyToManyField.symmetrical>`
  1026. -- therefore, there is the concept of a "source" and a "target". In that
  1027. case ``'field1'`` will be treated as the "source" of the relationship and
  1028. ``'field2'`` as the "target".
  1029. .. attribute:: ManyToManyField.db_table
  1030. The name of the table to create for storing the many-to-many data. If this
  1031. is not provided, Django will assume a default name based upon the names of:
  1032. the table for the model defining the relationship and the name of the field
  1033. itself.
  1034. .. attribute:: ManyToManyField.db_constraint
  1035. Controls whether or not constraints should be created in the database for
  1036. the foreign keys in the intermediary table. The default is ``True``, and
  1037. that's almost certainly what you want; setting this to ``False`` can be
  1038. very bad for data integrity. That said, here are some scenarios where you
  1039. might want to do this:
  1040. * You have legacy data that is not valid.
  1041. * You're sharding your database.
  1042. It is an error to pass both ``db_constraint`` and ``through``.
  1043. .. attribute:: ManyToManyField.swappable
  1044. .. versionadded:: 1.7
  1045. Controls the migration framework's reaction if this :class:`ManyToManyField`
  1046. is pointing at a swappable model. If it is ``True`` - the default -
  1047. then if the :class:`ManyToManyField` is pointing at a model which matches
  1048. the current value of ``settings.AUTH_USER_MODEL`` (or another swappable
  1049. model setting) the relationship will be stored in the migration using
  1050. a reference to the setting, not to the model directly.
  1051. You only want to override this to be ``False`` if you are sure your
  1052. model should always point towards the swapped-in model - for example,
  1053. if it is a profile model designed specifically for your custom user model.
  1054. If in doubt, leave it to its default of ``True``.
  1055. :class:`ManyToManyField` does not support :attr:`~Field.validators`.
  1056. :attr:`~Field.null` has no effect since there is no way to require a
  1057. relationship at the database level.
  1058. .. _ref-onetoone:
  1059. ``OneToOneField``
  1060. -----------------
  1061. .. class:: OneToOneField(othermodel, [parent_link=False, **options])
  1062. A one-to-one relationship. Conceptually, this is similar to a
  1063. :class:`ForeignKey` with :attr:`unique=True <Field.unique>`, but the
  1064. "reverse" side of the relation will directly return a single object.
  1065. This is most useful as the primary key of a model which "extends"
  1066. another model in some way; :ref:`multi-table-inheritance` is
  1067. implemented by adding an implicit one-to-one relation from the child
  1068. model to the parent model, for example.
  1069. One positional argument is required: the class to which the model will be
  1070. related. This works exactly the same as it does for :class:`ForeignKey`,
  1071. including all the options regarding :ref:`recursive <recursive-relationships>`
  1072. and :ref:`lazy <lazy-relationships>` relationships.
  1073. If you do not specify the :attr:`~ForeignKey.related_name` argument for
  1074. the ``OneToOneField``, Django will use the lower-case name of the current model
  1075. as default value.
  1076. With the following example::
  1077. from django.conf import settings
  1078. from django.db import models
  1079. class MySpecialUser(models.Model):
  1080. user = models.OneToOneField(settings.AUTH_USER_MODEL)
  1081. supervisor = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='supervisor_of')
  1082. your resulting ``User`` model will have the following attributes::
  1083. >>> user = User.objects.get(pk=1)
  1084. >>> hasattr(user, 'myspecialuser')
  1085. True
  1086. >>> hasattr(user, 'supervisor_of')
  1087. True
  1088. A ``DoesNotExist`` exception is raised when accessing the reverse relationship
  1089. if an entry in the related table doesn't exist. For example, if a user doesn't
  1090. have a supervisor designated by ``MySpecialUser``::
  1091. >>> user.supervisor_of
  1092. Traceback (most recent call last):
  1093. ...
  1094. DoesNotExist: User matching query does not exist.
  1095. .. _onetoone-arguments:
  1096. Additionally, ``OneToOneField`` accepts all of the extra arguments
  1097. accepted by :class:`ForeignKey`, plus one extra argument:
  1098. .. attribute:: OneToOneField.parent_link
  1099. When ``True`` and used in a model which inherits from another
  1100. :term:`concrete model`, indicates that this field should be used as the
  1101. link back to the parent class, rather than the extra
  1102. ``OneToOneField`` which would normally be implicitly created by
  1103. subclassing.
  1104. See :doc:`One-to-one relationships </topics/db/examples/one_to_one>` for usage
  1105. examples of ``OneToOneField``.
  1106. Field API reference
  1107. ===================
  1108. .. class:: Field
  1109. ``Field`` is an abstract class that represents a database table column.
  1110. Django uses fields to create the database table (:meth:`db_type`), to map
  1111. Python types to database (:meth:`get_prep_value`) and vice-versa
  1112. (:meth:`from_db_value`), and to apply :doc:`/ref/models/lookups`
  1113. (:meth:`get_prep_lookup`).
  1114. A field is thus a fundamental piece in different Django APIs, notably,
  1115. :class:`models <django.db.models.Model>` and :class:`querysets
  1116. <django.db.models.query.QuerySet>`.
  1117. In models, a field is instantiated as a class attribute and represents a
  1118. particular table column, see :doc:`/topics/db/models`. It has attributes
  1119. such as :attr:`null` and :attr:`unique`, and methods that Django uses to
  1120. map the field value to database-specific values.
  1121. A ``Field`` is a subclass of
  1122. :class:`~django.db.models.lookups.RegisterLookupMixin` and thus both
  1123. :class:`~django.db.models.Transform` and
  1124. :class:`~django.db.models.Lookup` can be registered on it to be used
  1125. in ``QuerySet``\s (e.g. ``field_name__exact="foo"``). All :ref:`built-in
  1126. lookups <field-lookups>` are registered by default.
  1127. All of Django's built-in fields, such as :class:`CharField`, are particular
  1128. implementations of ``Field``. If you need a custom field, you can either
  1129. subclass any of the built-in fields or write a ``Field``` from scratch. In
  1130. either case, see :doc:`/howto/custom-model-fields`.
  1131. .. attribute:: description
  1132. A verbose description of the field, e.g. for the
  1133. :mod:`django.contrib.admindocs` application.
  1134. The description can be of the form::
  1135. description = _("String (up to %(max_length)s)")
  1136. where the arguments are interpolated from the field's ``__dict__``.
  1137. To map a ``Field`` to a database-specific type, Django exposes two methods:
  1138. .. method:: get_internal_type()
  1139. Returns a string naming this field for backend specific purposes.
  1140. By default, it returns the class name.
  1141. See :ref:`emulating-built-in-field-types` for usage in custom fields.
  1142. .. method:: db_type(connection)
  1143. Returns the database column data type for the :class:`Field`, taking
  1144. into account the ``connection``.
  1145. See :ref:`custom-database-types` for usage in custom fields.
  1146. There are three main situations where Django needs to interact with the
  1147. database backend and fields:
  1148. * when it queries the database (Python value -> database backend value)
  1149. * when it loads data from the database (database backend value -> Python
  1150. value)
  1151. * when it saves to the database (Python value -> database backend value)
  1152. When querying, :meth:`get_db_prep_value` and :meth:`get_prep_value` are used:
  1153. .. method:: get_prep_value(value)
  1154. ``value`` is the current value of the model's attribute, and the method
  1155. should return data in a format that has been prepared for use as a
  1156. parameter in a query.
  1157. See :ref:`converting-python-objects-to-query-values` for usage.
  1158. .. method:: get_db_prep_value(value, connection, prepared=False)
  1159. Converts ``value`` to a backend-specific value. By default it returns
  1160. ``value`` if ``prepared=True`` and :meth:`~Field.get_prep_value` if is
  1161. ``False``.
  1162. See :ref:`converting-query-values-to-database-values` for usage.
  1163. When loading data, :meth:`from_db_value` is used:
  1164. .. method:: from_db_value(value, connection)
  1165. .. versionadded:: 1.8
  1166. Converts a value as returned by the database to a Python object. It is
  1167. the reverse of :meth:`get_prep_value`.
  1168. This method is not used for most built-in fields as the database
  1169. backend already returns the correct Python type, or the backend itself
  1170. does the conversion.
  1171. See :ref:`converting-values-to-python-objects` for usage.
  1172. .. note::
  1173. For performance reasons, ``from_db_value`` is not implemented as a
  1174. no-op on fields which do not require it (all Django fields).
  1175. Consequently you may not call ``super`` in your definition.
  1176. When saving, :meth:`pre_save` and :meth:`get_db_prep_save` are used:
  1177. .. method:: get_db_prep_save(value, connection)
  1178. Same as the :meth:`get_db_prep_value`, but called when the field value
  1179. must be *saved* to the database. By default returns
  1180. :meth:`get_db_prep_value`.
  1181. .. method:: pre_save(model_instance, add)
  1182. Method called prior to :meth:`get_db_prep_save` to prepare the value
  1183. before being saved (e.g. for :attr:`DateField.auto_now`).
  1184. ``model_instance`` is the instance this field belongs to and ``add``
  1185. is whether the instance is being saved to the database for the first
  1186. time.
  1187. It should return the value of the appropriate attribute from
  1188. ``model_instance`` for this field. The attribute name is in
  1189. ``self.attname`` (this is set up by :class:`~django.db.models.Field`).
  1190. See :ref:`preprocessing-values-before-saving` for usage.
  1191. When a lookup is used on a field, the value may need to be "prepared".
  1192. Django exposes two methods for this:
  1193. .. method:: get_prep_lookup(lookup_type, value)
  1194. Prepares ``value`` to the database prior to be used in a lookup.
  1195. The ``lookup_type`` will be one of the valid Django filter lookups:
  1196. ``"exact"``, ``"iexact"``, ``"contains"``, ``"icontains"``,
  1197. ``"gt"``, ``"gte"``, ``"lt"``, ``"lte"``, ``"in"``, ``"startswith"``,
  1198. ``"istartswith"``, ``"endswith"``, ``"iendswith"``, ``"range"``,
  1199. ``"year"``, ``"month"``, ``"day"``, ``"isnull"``, ``"search"``,
  1200. ``"regex"``, and ``"iregex"``.
  1201. .. versionadded:: 1.7
  1202. If you are using :doc:`Custom lookups </ref/models/lookups>` the
  1203. ``lookup_type`` can be any ``lookup_name`` registered in the field.
  1204. See :ref:`preparing-values-for-use-in-database-lookups` for usage.
  1205. .. method:: get_db_prep_lookup(lookup_type, value, connection, prepared=False)
  1206. Similar to :meth:`get_db_prep_value`, but for performing a lookup.
  1207. As with :meth:`get_db_prep_value`, the specific connection that will
  1208. be used for the query is passed as ``connection``. In addition,
  1209. ``prepared`` describes whether the value has already been prepared with
  1210. :meth:`get_prep_lookup`.
  1211. Fields often receive their values as a different type, either from
  1212. serialization or from forms.
  1213. .. method:: to_python(value)
  1214. Converts the value into the correct Python object. It acts as the
  1215. reverse of :meth:`value_to_string`, and is also called in
  1216. :meth:`~django.db.models.Model.clean`.
  1217. See :ref:`converting-values-to-python-objects` for usage.
  1218. Besides saving to the database, the field also needs to know how to
  1219. serialize its value:
  1220. .. method:: value_to_string(obj)
  1221. Converts ``obj`` to a string. Used to serialize the value of the field.
  1222. See :ref:`converting-model-field-to-serialization` for usage.
  1223. When using :class:`model forms <django.forms.ModelForm>`, the ``Field``
  1224. needs to know which form field it should be represented by:
  1225. .. method:: formfield(form_class=None, choices_form_class=None, **kwargs)
  1226. Returns the default :class:`django.forms.Field` of this field for
  1227. :class:`~django.forms.ModelForm`.
  1228. By default, if both ``form_class`` and ``choices_form_class`` are
  1229. ``None``, it uses :class:`~django.forms.CharField`; if
  1230. ``choices_form_class`` is given, it returns
  1231. :class:`~django.forms.TypedChoiceField`.
  1232. See :ref:`specifying-form-field-for-model-field` for usage.
  1233. .. method:: deconstruct()
  1234. .. versionadded:: 1.7
  1235. Returns a 4-tuple with enough information to recreate the field:
  1236. 1. The name of the field on the model.
  1237. 2. The import path of the field (e.g. ``"django.db.models.IntegerField"``).
  1238. This should be the most portable version, so less specific may be better.
  1239. 3. A list of positional arguments.
  1240. 4. A dict of keyword arguments.
  1241. This method must be added to fields prior to 1.7 to migrate its data
  1242. using :doc:`/topics/migrations`.
  1243. .. _model-field-attributes:
  1244. =========================
  1245. Field attribute reference
  1246. =========================
  1247. .. versionadded:: 1.8
  1248. Every ``Field`` instance contains several attributes that allow
  1249. introspecting its behavior. Use these attributes instead of ``isinstance``
  1250. checks when you need to write code that depends on a field's functionality.
  1251. These attributes can be used together with the :ref:`Model._meta API
  1252. <model-meta-field-api>` to narrow down a search for specific field types.
  1253. Custom model fields should implement these flags.
  1254. Attributes for fields
  1255. =====================
  1256. .. attribute:: Field.auto_created
  1257. Boolean flag that indicates if the field was automatically created, such
  1258. as the ``OneToOneField`` used by model inheritance.
  1259. .. attribute:: Field.concrete
  1260. Boolean flag that indicates if the field has a database column associated
  1261. with it.
  1262. .. attribute:: Field.hidden
  1263. Boolean flag that indicates if a field is used to back another non-hidden
  1264. field's functionality (e.g. the ``content_type`` and ``object_id`` fields
  1265. that make up a ``GenericForeignKey``). The ``hidden`` flag is used to
  1266. distinguish what constitutes the public subset of fields on the model from
  1267. all the fields on the model.
  1268. .. note::
  1269. :meth:`Options.get_fields()
  1270. <django.db.models.options.Options.get_fields()>`
  1271. excludes hidden fields by default. Pass in ``include_hidden=True`` to
  1272. return hidden fields in the results.
  1273. .. attribute:: Field.is_relation
  1274. Boolean flag that indicates if a field contains references to one or
  1275. more other models for its functionality (e.g. ``ForeignKey``,
  1276. ``ManyToManyField``, ``OneToOneField``, etc.).
  1277. .. attribute:: Field.model
  1278. Returns the model on which the field is defined. If a field is defined on
  1279. a superclass of a model, ``model`` will refer to the superclass, not the
  1280. class of the instance.
  1281. Attributes for fields with relations
  1282. ====================================
  1283. These attributes are used to query for the cardinality and other details of a
  1284. relation. These attribute are present on all fields; however, they will only
  1285. have meaningful values if the field is a relation type
  1286. (:attr:`Field.is_relation=True <Field.is_relation>`).
  1287. .. attribute:: Field.one_to_many
  1288. Boolean flag that is ``True`` if the field has a one-to-many relation, such
  1289. as a ``ForeignKey``; ``False`` otherwise.
  1290. .. attribute:: Field.one_to_one
  1291. Boolean flag that is ``True`` if the field has a one-to-one relation, such
  1292. as a ``OneToOneField``; ``False`` otherwise.
  1293. .. attribute:: Field.many_to_many
  1294. Boolean flag that is ``True`` if the field has a many-to-many relation;
  1295. ``False`` otherwise. The only field included with Django where this is
  1296. ``True`` is ``ManyToManyField``.
  1297. .. attribute:: Field.many_to_one
  1298. Boolean flag that is ``True`` if the field has a many-to-one relation, such
  1299. as a ``GenericRelation`` or the reverse of a ``ForeignKey``; ``False``
  1300. otherwise.
  1301. .. attribute:: Field.related_model
  1302. Points to the model the field relates to. For example, ``Author`` in
  1303. ``ForeignKey(Author)``. If a field has a generic relation (such as a
  1304. ``GenericForeignKey`` or a ``GenericRelation``) then ``related_model``
  1305. will be ``None``.