models.txt 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623
  1. ======
  2. Models
  3. ======
  4. .. module:: django.db.models
  5. A model is the single, definitive source of information about your data. It
  6. contains the essential fields and behaviors of the data you're storing.
  7. Generally, each model maps to a single database table.
  8. The basics:
  9. * Each model is a Python class that subclasses
  10. :class:`django.db.models.Model`.
  11. * Each attribute of the model represents a database field.
  12. * With all of this, Django gives you an automatically-generated
  13. database-access API; see :doc:`/topics/db/queries`.
  14. Quick example
  15. =============
  16. This example model defines a ``Person``, which has a ``first_name`` and
  17. ``last_name``::
  18. from django.db import models
  19. class Person(models.Model):
  20. first_name = models.CharField(max_length=30)
  21. last_name = models.CharField(max_length=30)
  22. ``first_name`` and ``last_name`` are fields_ of the model. Each field is
  23. specified as a class attribute, and each attribute maps to a database column.
  24. The above ``Person`` model would create a database table like this:
  25. .. code-block:: sql
  26. CREATE TABLE myapp_person (
  27. "id" bigint NOT NULL PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
  28. "first_name" varchar(30) NOT NULL,
  29. "last_name" varchar(30) NOT NULL
  30. );
  31. Some technical notes:
  32. * The name of the table, ``myapp_person``, is automatically derived from
  33. some model metadata but can be overridden. See :ref:`table-names` for more
  34. details.
  35. * An ``id`` field is added automatically, but this behavior can be
  36. overridden. See :ref:`automatic-primary-key-fields`.
  37. * The ``CREATE TABLE`` SQL in this example is formatted using PostgreSQL
  38. syntax, but it's worth noting Django uses SQL tailored to the database
  39. backend specified in your :doc:`settings file </topics/settings>`.
  40. Using models
  41. ============
  42. Once you have defined your models, you need to tell Django you're going to *use*
  43. those models. Do this by editing your settings file and changing the
  44. :setting:`INSTALLED_APPS` setting to add the name of the module that contains
  45. your ``models.py``.
  46. For example, if the models for your application live in the module
  47. ``myapp.models`` (the package structure that is created for an
  48. application by the :djadmin:`manage.py startapp <startapp>` script),
  49. :setting:`INSTALLED_APPS` should read, in part::
  50. INSTALLED_APPS = [
  51. # ...
  52. "myapp",
  53. # ...
  54. ]
  55. When you add new apps to :setting:`INSTALLED_APPS`, be sure to run
  56. :djadmin:`manage.py migrate <migrate>`, optionally making migrations
  57. for them first with :djadmin:`manage.py makemigrations <makemigrations>`.
  58. Fields
  59. ======
  60. The most important part of a model -- and the only required part of a model --
  61. is the list of database fields it defines. Fields are specified by class
  62. attributes. Be careful not to choose field names that conflict with the
  63. :doc:`models API </ref/models/instances>` like ``clean``, ``save``, or
  64. ``delete``.
  65. Example::
  66. from django.db import models
  67. class Musician(models.Model):
  68. first_name = models.CharField(max_length=50)
  69. last_name = models.CharField(max_length=50)
  70. instrument = models.CharField(max_length=100)
  71. class Album(models.Model):
  72. artist = models.ForeignKey(Musician, on_delete=models.CASCADE)
  73. name = models.CharField(max_length=100)
  74. release_date = models.DateField()
  75. num_stars = models.IntegerField()
  76. Field types
  77. -----------
  78. Each field in your model should be an instance of the appropriate
  79. :class:`~django.db.models.Field` class. Django uses the field class types to
  80. determine a few things:
  81. * The column type, which tells the database what kind of data to store (e.g.
  82. ``INTEGER``, ``VARCHAR``, ``TEXT``).
  83. * The default HTML :doc:`widget </ref/forms/widgets>` to use when rendering a form
  84. field (e.g. ``<input type="text">``, ``<select>``).
  85. * The minimal validation requirements, used in Django's admin and in
  86. automatically-generated forms.
  87. Django ships with dozens of built-in field types; you can find the complete list
  88. in the :ref:`model field reference <model-field-types>`. You can easily write
  89. your own fields if Django's built-in ones don't do the trick; see
  90. :doc:`/howto/custom-model-fields`.
  91. Field options
  92. -------------
  93. Each field takes a certain set of field-specific arguments (documented in the
  94. :ref:`model field reference <model-field-types>`). For example,
  95. :class:`~django.db.models.CharField` (and its subclasses) require a
  96. :attr:`~django.db.models.CharField.max_length` argument which specifies the size
  97. of the ``VARCHAR`` database field used to store the data.
  98. There's also a set of common arguments available to all field types. All are
  99. optional. They're fully explained in the :ref:`reference
  100. <common-model-field-options>`, but here's a quick summary of the most often-used
  101. ones:
  102. :attr:`~Field.null`
  103. If ``True``, Django will store empty values as ``NULL`` in the database.
  104. Default is ``False``.
  105. :attr:`~Field.blank`
  106. If ``True``, the field is allowed to be blank. Default is ``False``.
  107. Note that this is different than :attr:`~Field.null`.
  108. :attr:`~Field.null` is purely database-related, whereas
  109. :attr:`~Field.blank` is validation-related. If a field has
  110. :attr:`blank=True <Field.blank>`, form validation will
  111. allow entry of an empty value. If a field has :attr:`blank=False
  112. <Field.blank>`, the field will be required.
  113. :attr:`~Field.choices`
  114. A :term:`sequence` of 2-value tuples, a :term:`mapping`, an
  115. :ref:`enumeration type <field-choices-enum-types>`, or a callable (that
  116. expects no arguments and returns any of the previous formats), to use as
  117. choices for this field. If this is given, the default form widget will be a
  118. select box instead of the standard text field and will limit choices to the
  119. choices given.
  120. A choices list looks like this::
  121. YEAR_IN_SCHOOL_CHOICES = [
  122. ("FR", "Freshman"),
  123. ("SO", "Sophomore"),
  124. ("JR", "Junior"),
  125. ("SR", "Senior"),
  126. ("GR", "Graduate"),
  127. ]
  128. .. note::
  129. A new migration is created each time the order of ``choices`` changes.
  130. The first element in each tuple is the value that will be stored in the
  131. database. The second element is displayed by the field's form widget.
  132. Given a model instance, the display value for a field with ``choices`` can
  133. be accessed using the :meth:`~django.db.models.Model.get_FOO_display`
  134. method. For example::
  135. from django.db import models
  136. class Person(models.Model):
  137. SHIRT_SIZES = {
  138. "S": "Small",
  139. "M": "Medium",
  140. "L": "Large",
  141. }
  142. name = models.CharField(max_length=60)
  143. shirt_size = models.CharField(max_length=1, choices=SHIRT_SIZES)
  144. .. code-block:: pycon
  145. >>> p = Person(name="Fred Flintstone", shirt_size="L")
  146. >>> p.save()
  147. >>> p.shirt_size
  148. 'L'
  149. >>> p.get_shirt_size_display()
  150. 'Large'
  151. You can also use enumeration classes to define ``choices`` in a concise
  152. way::
  153. from django.db import models
  154. class Runner(models.Model):
  155. MedalType = models.TextChoices("MedalType", "GOLD SILVER BRONZE")
  156. name = models.CharField(max_length=60)
  157. medal = models.CharField(blank=True, choices=MedalType, max_length=10)
  158. Further examples are available in the :ref:`model field reference
  159. <field-choices>`.
  160. :attr:`~Field.default`
  161. The default value for the field. This can be a value or a callable
  162. object. If callable it will be called every time a new object is
  163. created.
  164. :attr:`~Field.db_default`
  165. The database-computed default value for the field. This can be a literal
  166. value or a database function.
  167. If both ``db_default`` and :attr:`Field.default` are set, ``default`` will
  168. take precedence when creating instances in Python code. ``db_default`` will
  169. still be set at the database level and will be used when inserting rows
  170. outside of the ORM or when adding a new field in a migration.
  171. :attr:`~Field.help_text`
  172. Extra "help" text to be displayed with the form widget. It's useful for
  173. documentation even if your field isn't used on a form.
  174. :attr:`~Field.primary_key`
  175. If ``True``, this field is the primary key for the model.
  176. If you don't specify :attr:`primary_key=True <Field.primary_key>` for
  177. any fields in your model, Django will automatically add a field to hold
  178. the primary key, so you don't need to set
  179. :attr:`primary_key=True <Field.primary_key>` on any of your fields
  180. unless you want to override the default primary-key behavior. For more,
  181. see :ref:`automatic-primary-key-fields`.
  182. The primary key field is read-only. If you change the value of the primary
  183. key on an existing object and then save it, a new object will be created
  184. alongside the old one. For example::
  185. from django.db import models
  186. class Fruit(models.Model):
  187. name = models.CharField(max_length=100, primary_key=True)
  188. .. code-block:: pycon
  189. >>> fruit = Fruit.objects.create(name="Apple")
  190. >>> fruit.name = "Pear"
  191. >>> fruit.save()
  192. >>> Fruit.objects.values_list("name", flat=True)
  193. <QuerySet ['Apple', 'Pear']>
  194. :attr:`~Field.unique`
  195. If ``True``, this field must be unique throughout the table.
  196. Again, these are just short descriptions of the most common field options. Full
  197. details can be found in the :ref:`common model field option reference
  198. <common-model-field-options>`.
  199. .. _automatic-primary-key-fields:
  200. Automatic primary key fields
  201. ----------------------------
  202. By default, Django gives each model an auto-incrementing primary key with the
  203. type specified per app in :attr:`AppConfig.default_auto_field
  204. <django.apps.AppConfig.default_auto_field>` or globally in the
  205. :setting:`DEFAULT_AUTO_FIELD` setting. For example::
  206. id = models.BigAutoField(primary_key=True)
  207. If you'd like to specify a custom primary key, specify
  208. :attr:`primary_key=True <Field.primary_key>` on one of your fields. If Django
  209. sees you've explicitly set :attr:`Field.primary_key`, it won't add the automatic
  210. ``id`` column.
  211. Each model requires exactly one field to have :attr:`primary_key=True
  212. <Field.primary_key>` (either explicitly declared or automatically added).
  213. .. _verbose-field-names:
  214. Verbose field names
  215. -------------------
  216. Each field type, except for :class:`~django.db.models.ForeignKey`,
  217. :class:`~django.db.models.ManyToManyField` and
  218. :class:`~django.db.models.OneToOneField`, takes an optional first positional
  219. argument -- a verbose name. If the verbose name isn't given, Django will
  220. automatically create it using the field's attribute name, converting underscores
  221. to spaces.
  222. In this example, the verbose name is ``"person's first name"``::
  223. first_name = models.CharField("person's first name", max_length=30)
  224. In this example, the verbose name is ``"first name"``::
  225. first_name = models.CharField(max_length=30)
  226. :class:`~django.db.models.ForeignKey`,
  227. :class:`~django.db.models.ManyToManyField` and
  228. :class:`~django.db.models.OneToOneField` require the first argument to be a
  229. model class, so use the :attr:`~Field.verbose_name` keyword argument::
  230. poll = models.ForeignKey(
  231. Poll,
  232. on_delete=models.CASCADE,
  233. verbose_name="the related poll",
  234. )
  235. sites = models.ManyToManyField(Site, verbose_name="list of sites")
  236. place = models.OneToOneField(
  237. Place,
  238. on_delete=models.CASCADE,
  239. verbose_name="related place",
  240. )
  241. The convention is not to capitalize the first letter of the
  242. :attr:`~Field.verbose_name`. Django will automatically capitalize the first
  243. letter where it needs to.
  244. Relationships
  245. -------------
  246. Clearly, the power of relational databases lies in relating tables to each
  247. other. Django offers ways to define the three most common types of database
  248. relationships: many-to-one, many-to-many and one-to-one.
  249. Many-to-one relationships
  250. ~~~~~~~~~~~~~~~~~~~~~~~~~
  251. To define a many-to-one relationship, use :class:`django.db.models.ForeignKey`.
  252. You use it just like any other :class:`~django.db.models.Field` type: by
  253. including it as a class attribute of your model.
  254. :class:`~django.db.models.ForeignKey` requires a positional argument: the class
  255. to which the model is related.
  256. For example, if a ``Car`` model has a ``Manufacturer`` -- that is, a
  257. ``Manufacturer`` makes multiple cars but each ``Car`` only has one
  258. ``Manufacturer`` -- use the following definitions::
  259. from django.db import models
  260. class Manufacturer(models.Model):
  261. # ...
  262. pass
  263. class Car(models.Model):
  264. manufacturer = models.ForeignKey(Manufacturer, on_delete=models.CASCADE)
  265. # ...
  266. You can also create :ref:`recursive relationships <recursive-relationships>` (an
  267. object with a many-to-one relationship to itself) and :ref:`relationships to
  268. models not yet defined <lazy-relationships>`; see :ref:`the model field
  269. reference <ref-foreignkey>` for details.
  270. It's suggested, but not required, that the name of a
  271. :class:`~django.db.models.ForeignKey` field (``manufacturer`` in the example
  272. above) be the name of the model, lowercase. You can call the field whatever you
  273. want. For example::
  274. class Car(models.Model):
  275. company_that_makes_it = models.ForeignKey(
  276. Manufacturer,
  277. on_delete=models.CASCADE,
  278. )
  279. # ...
  280. .. seealso::
  281. :class:`~django.db.models.ForeignKey` fields accept a number of extra
  282. arguments which are explained in :ref:`the model field reference
  283. <foreign-key-arguments>`. These options help define how the relationship
  284. should work; all are optional.
  285. For details on accessing backwards-related objects, see the
  286. :ref:`Following relationships backward example <backwards-related-objects>`.
  287. For sample code, see the :doc:`Many-to-one relationship model example
  288. </topics/db/examples/many_to_one>`.
  289. Many-to-many relationships
  290. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  291. To define a many-to-many relationship, use
  292. :class:`~django.db.models.ManyToManyField`. You use it just like any other
  293. :class:`~django.db.models.Field` type: by including it as a class attribute of
  294. your model.
  295. :class:`~django.db.models.ManyToManyField` requires a positional argument: the
  296. class to which the model is related.
  297. For example, if a ``Pizza`` has multiple ``Topping`` objects -- that is, a
  298. ``Topping`` can be on multiple pizzas and each ``Pizza`` has multiple toppings
  299. -- here's how you'd represent that::
  300. from django.db import models
  301. class Topping(models.Model):
  302. # ...
  303. pass
  304. class Pizza(models.Model):
  305. # ...
  306. toppings = models.ManyToManyField(Topping)
  307. As with :class:`~django.db.models.ForeignKey`, you can also create
  308. :ref:`recursive relationships <recursive-relationships>` (an object with a
  309. many-to-many relationship to itself) and :ref:`relationships to models not yet
  310. defined <lazy-relationships>`.
  311. It's suggested, but not required, that the name of a
  312. :class:`~django.db.models.ManyToManyField` (``toppings`` in the example above)
  313. be a plural describing the set of related model objects.
  314. It doesn't matter which model has the
  315. :class:`~django.db.models.ManyToManyField`, but you should only put it in one
  316. of the models -- not both.
  317. Generally, :class:`~django.db.models.ManyToManyField` instances should go in
  318. the object that's going to be edited on a form. In the above example,
  319. ``toppings`` is in ``Pizza`` (rather than ``Topping`` having a ``pizzas``
  320. :class:`~django.db.models.ManyToManyField` ) because it's more natural to think
  321. about a pizza having toppings than a topping being on multiple pizzas. The way
  322. it's set up above, the ``Pizza`` form would let users select the toppings.
  323. .. seealso::
  324. See the :doc:`Many-to-many relationship model example
  325. </topics/db/examples/many_to_many>` for a full example.
  326. :class:`~django.db.models.ManyToManyField` fields also accept a number of
  327. extra arguments which are explained in :ref:`the model field reference
  328. <manytomany-arguments>`. These options help define how the relationship
  329. should work; all are optional.
  330. .. _intermediary-manytomany:
  331. Extra fields on many-to-many relationships
  332. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  333. When you're only dealing with many-to-many relationships such as mixing and
  334. matching pizzas and toppings, a standard
  335. :class:`~django.db.models.ManyToManyField` is all you need. However, sometimes
  336. you may need to associate data with the relationship between two models.
  337. For example, consider the case of an application tracking the musical groups
  338. which musicians belong to. There is a many-to-many relationship between a person
  339. and the groups of which they are a member, so you could use a
  340. :class:`~django.db.models.ManyToManyField` to represent this relationship.
  341. However, there is a lot of detail about the membership that you might want to
  342. collect, such as the date at which the person joined the group.
  343. For these situations, Django allows you to specify the model that will be used
  344. to govern the many-to-many relationship. You can then put extra fields on the
  345. intermediate model. The intermediate model is associated with the
  346. :class:`~django.db.models.ManyToManyField` using the
  347. :attr:`through <ManyToManyField.through>` argument to point to the model
  348. that will act as an intermediary. For our musician example, the code would look
  349. something like this::
  350. from django.db import models
  351. class Person(models.Model):
  352. name = models.CharField(max_length=128)
  353. def __str__(self):
  354. return self.name
  355. class Group(models.Model):
  356. name = models.CharField(max_length=128)
  357. members = models.ManyToManyField(Person, through="Membership")
  358. def __str__(self):
  359. return self.name
  360. class Membership(models.Model):
  361. person = models.ForeignKey(Person, on_delete=models.CASCADE)
  362. group = models.ForeignKey(Group, on_delete=models.CASCADE)
  363. date_joined = models.DateField()
  364. invite_reason = models.CharField(max_length=64)
  365. class Meta:
  366. constraints = [
  367. models.UniqueConstraint(
  368. fields=["person", "group"], name="unique_person_group"
  369. )
  370. ]
  371. When you set up the intermediary model, you explicitly specify foreign
  372. keys to the models that are involved in the many-to-many relationship. This
  373. explicit declaration defines how the two models are related.
  374. If you don't want multiple associations between the same instances, add a
  375. :class:`~django.db.models.UniqueConstraint` including the ``from`` and ``to``
  376. fields. Django's automatically generated many-to-many tables include such a
  377. constraint.
  378. There are a few restrictions on the intermediate model:
  379. * Your intermediate model must contain one - and *only* one - foreign key
  380. to the source model (this would be ``Group`` in our example), or you must
  381. explicitly specify the foreign keys Django should use for the relationship
  382. using :attr:`ManyToManyField.through_fields <ManyToManyField.through_fields>`.
  383. If you have more than one foreign key and ``through_fields`` is not
  384. specified, a validation error will be raised. A similar restriction applies
  385. to the foreign key to the target model (this would be ``Person`` in our
  386. example).
  387. * For a model which has a many-to-many relationship to itself through an
  388. intermediary model, two foreign keys to the same model are permitted, but
  389. they will be treated as the two (different) sides of the many-to-many
  390. relationship. If there are *more* than two foreign keys though, you
  391. must also specify ``through_fields`` as above, or a validation error
  392. will be raised.
  393. Now that you have set up your :class:`~django.db.models.ManyToManyField` to use
  394. your intermediary model (``Membership``, in this case), you're ready to start
  395. creating some many-to-many relationships. You do this by creating instances of
  396. the intermediate model:
  397. .. code-block:: pycon
  398. >>> ringo = Person.objects.create(name="Ringo Starr")
  399. >>> paul = Person.objects.create(name="Paul McCartney")
  400. >>> beatles = Group.objects.create(name="The Beatles")
  401. >>> m1 = Membership(
  402. ... person=ringo,
  403. ... group=beatles,
  404. ... date_joined=date(1962, 8, 16),
  405. ... invite_reason="Needed a new drummer.",
  406. ... )
  407. >>> m1.save()
  408. >>> beatles.members.all()
  409. <QuerySet [<Person: Ringo Starr>]>
  410. >>> ringo.group_set.all()
  411. <QuerySet [<Group: The Beatles>]>
  412. >>> m2 = Membership.objects.create(
  413. ... person=paul,
  414. ... group=beatles,
  415. ... date_joined=date(1960, 8, 1),
  416. ... invite_reason="Wanted to form a band.",
  417. ... )
  418. >>> beatles.members.all()
  419. <QuerySet [<Person: Ringo Starr>, <Person: Paul McCartney>]>
  420. You can also use :meth:`~django.db.models.fields.related.RelatedManager.add`,
  421. :meth:`~django.db.models.fields.related.RelatedManager.create`, or
  422. :meth:`~django.db.models.fields.related.RelatedManager.set` to create
  423. relationships, as long as you specify ``through_defaults`` for any required
  424. fields:
  425. .. code-block:: pycon
  426. >>> beatles.members.add(john, through_defaults={"date_joined": date(1960, 8, 1)})
  427. >>> beatles.members.create(
  428. ... name="George Harrison", through_defaults={"date_joined": date(1960, 8, 1)}
  429. ... )
  430. >>> beatles.members.set(
  431. ... [john, paul, ringo, george], through_defaults={"date_joined": date(1960, 8, 1)}
  432. ... )
  433. You may prefer to create instances of the intermediate model directly.
  434. If the custom through table defined by the intermediate model does not enforce
  435. uniqueness on the ``(model1, model2)`` pair, allowing multiple values, the
  436. :meth:`~django.db.models.fields.related.RelatedManager.remove` call will
  437. remove all intermediate model instances:
  438. .. code-block:: pycon
  439. >>> Membership.objects.create(
  440. ... person=ringo,
  441. ... group=beatles,
  442. ... date_joined=date(1968, 9, 4),
  443. ... invite_reason="You've been gone for a month and we miss you.",
  444. ... )
  445. >>> beatles.members.all()
  446. <QuerySet [<Person: Ringo Starr>, <Person: Paul McCartney>, <Person: Ringo Starr>]>
  447. >>> # This deletes both of the intermediate model instances for Ringo Starr
  448. >>> beatles.members.remove(ringo)
  449. >>> beatles.members.all()
  450. <QuerySet [<Person: Paul McCartney>]>
  451. The :meth:`~django.db.models.fields.related.RelatedManager.clear`
  452. method can be used to remove all many-to-many relationships for an instance:
  453. .. code-block:: pycon
  454. >>> # Beatles have broken up
  455. >>> beatles.members.clear()
  456. >>> # Note that this deletes the intermediate model instances
  457. >>> Membership.objects.all()
  458. <QuerySet []>
  459. Once you have established the many-to-many relationships, you can issue
  460. queries. Just as with normal many-to-many relationships, you can query using
  461. the attributes of the many-to-many-related model:
  462. .. code-block:: pycon
  463. # Find all the groups with a member whose name starts with 'Paul'
  464. >>> Group.objects.filter(members__name__startswith="Paul")
  465. <QuerySet [<Group: The Beatles>]>
  466. As you are using an intermediate model, you can also query on its attributes:
  467. .. code-block:: pycon
  468. # Find all the members of the Beatles that joined after 1 Jan 1961
  469. >>> Person.objects.filter(
  470. ... group__name="The Beatles", membership__date_joined__gt=date(1961, 1, 1)
  471. ... )
  472. <QuerySet [<Person: Ringo Starr]>
  473. If you need to access a membership's information you may do so by directly
  474. querying the ``Membership`` model:
  475. .. code-block:: pycon
  476. >>> ringos_membership = Membership.objects.get(group=beatles, person=ringo)
  477. >>> ringos_membership.date_joined
  478. datetime.date(1962, 8, 16)
  479. >>> ringos_membership.invite_reason
  480. 'Needed a new drummer.'
  481. Another way to access the same information is by querying the
  482. :ref:`many-to-many reverse relationship<m2m-reverse-relationships>` from a
  483. ``Person`` object:
  484. .. code-block:: pycon
  485. >>> ringos_membership = ringo.membership_set.get(group=beatles)
  486. >>> ringos_membership.date_joined
  487. datetime.date(1962, 8, 16)
  488. >>> ringos_membership.invite_reason
  489. 'Needed a new drummer.'
  490. One-to-one relationships
  491. ~~~~~~~~~~~~~~~~~~~~~~~~
  492. To define a one-to-one relationship, use
  493. :class:`~django.db.models.OneToOneField`. You use it just like any other
  494. ``Field`` type: by including it as a class attribute of your model.
  495. This is most useful on the primary key of an object when that object "extends"
  496. another object in some way.
  497. :class:`~django.db.models.OneToOneField` requires a positional argument: the
  498. class to which the model is related.
  499. For example, if you were building a database of "places", you would
  500. build pretty standard stuff such as address, phone number, etc. in the
  501. database. Then, if you wanted to build a database of restaurants on
  502. top of the places, instead of repeating yourself and replicating those
  503. fields in the ``Restaurant`` model, you could make ``Restaurant`` have
  504. a :class:`~django.db.models.OneToOneField` to ``Place`` (because a
  505. restaurant "is a" place; in fact, to handle this you'd typically use
  506. :ref:`inheritance <model-inheritance>`, which involves an implicit
  507. one-to-one relation).
  508. As with :class:`~django.db.models.ForeignKey`, a :ref:`recursive relationship
  509. <recursive-relationships>` can be defined and :ref:`references to as-yet
  510. undefined models <lazy-relationships>` can be made.
  511. .. seealso::
  512. See the :doc:`One-to-one relationship model example
  513. </topics/db/examples/one_to_one>` for a full example.
  514. :class:`~django.db.models.OneToOneField` fields also accept an optional
  515. :attr:`~django.db.models.OneToOneField.parent_link` argument.
  516. :class:`~django.db.models.OneToOneField` classes used to automatically become
  517. the primary key on a model. This is no longer true (although you can manually
  518. pass in the :attr:`~django.db.models.Field.primary_key` argument if you like).
  519. Thus, it's now possible to have multiple fields of type
  520. :class:`~django.db.models.OneToOneField` on a single model.
  521. Models across files
  522. -------------------
  523. It's perfectly OK to relate a model to one from another app. To do this, import
  524. the related model at the top of the file where your model is defined. Then,
  525. refer to the other model class wherever needed. For example::
  526. from django.db import models
  527. from geography.models import ZipCode
  528. class Restaurant(models.Model):
  529. # ...
  530. zip_code = models.ForeignKey(
  531. ZipCode,
  532. on_delete=models.SET_NULL,
  533. blank=True,
  534. null=True,
  535. )
  536. Field name restrictions
  537. -----------------------
  538. Django places some restrictions on model field names:
  539. #. A field name cannot be a Python reserved word, because that would result
  540. in a Python syntax error. For example:
  541. .. code-block:: text
  542. class Example(models.Model):
  543. pass = models.IntegerField() # 'pass' is a reserved word!
  544. #. A field name cannot contain more than one underscore in a row, due to
  545. the way Django's query lookup syntax works. For example::
  546. class Example(models.Model):
  547. foo__bar = models.IntegerField() # 'foo__bar' has two underscores!
  548. #. A field name cannot end with an underscore, for similar reasons.
  549. #. A field name cannot be ``check``, as this would override the check
  550. framework's ``Model.check()`` method.
  551. These limitations can be worked around, though, because your field name doesn't
  552. necessarily have to match your database column name. See the
  553. :attr:`~Field.db_column` option.
  554. SQL reserved words, such as ``join``, ``where`` or ``select``, *are* allowed as
  555. model field names, because Django escapes all database table names and column
  556. names in every underlying SQL query. It uses the quoting syntax of your
  557. particular database engine.
  558. Custom field types
  559. ------------------
  560. If one of the existing model fields cannot be used to fit your purposes, or if
  561. you wish to take advantage of some less common database column types, you can
  562. create your own field class. Full coverage of creating your own fields is
  563. provided in :doc:`/howto/custom-model-fields`.
  564. .. _meta-options:
  565. ``Meta`` options
  566. ================
  567. Give your model metadata by using an inner ``class Meta``, like so::
  568. from django.db import models
  569. class Ox(models.Model):
  570. horn_length = models.IntegerField()
  571. class Meta:
  572. ordering = ["horn_length"]
  573. verbose_name_plural = "oxen"
  574. Model metadata is "anything that's not a field", such as ordering options
  575. (:attr:`~Options.ordering`), database table name (:attr:`~Options.db_table`), or
  576. human-readable singular and plural names (:attr:`~Options.verbose_name` and
  577. :attr:`~Options.verbose_name_plural`). None are required, and adding ``class
  578. Meta`` to a model is completely optional.
  579. A complete list of all possible ``Meta`` options can be found in the :doc:`model
  580. option reference </ref/models/options>`.
  581. .. _model-attributes:
  582. Model attributes
  583. ================
  584. ``objects``
  585. The most important attribute of a model is the
  586. :class:`~django.db.models.Manager`. It's the interface through which
  587. database query operations are provided to Django models and is used to
  588. :ref:`retrieve the instances <retrieving-objects>` from the database. If no
  589. custom ``Manager`` is defined, the default name is
  590. :attr:`~django.db.models.Model.objects`. Managers are only accessible via
  591. model classes, not the model instances.
  592. .. _model-methods:
  593. Model methods
  594. =============
  595. Define custom methods on a model to add custom "row-level" functionality to your
  596. objects. Whereas :class:`~django.db.models.Manager` methods are intended to do
  597. "table-wide" things, model methods should act on a particular model instance.
  598. This is a valuable technique for keeping business logic in one place -- the
  599. model.
  600. For example, this model has a few custom methods::
  601. from django.db import models
  602. class Person(models.Model):
  603. first_name = models.CharField(max_length=50)
  604. last_name = models.CharField(max_length=50)
  605. birth_date = models.DateField()
  606. def baby_boomer_status(self):
  607. "Returns the person's baby-boomer status."
  608. import datetime
  609. if self.birth_date < datetime.date(1945, 8, 1):
  610. return "Pre-boomer"
  611. elif self.birth_date < datetime.date(1965, 1, 1):
  612. return "Baby boomer"
  613. else:
  614. return "Post-boomer"
  615. @property
  616. def full_name(self):
  617. "Returns the person's full name."
  618. return f"{self.first_name} {self.last_name}"
  619. The last method in this example is a :term:`property`.
  620. The :doc:`model instance reference </ref/models/instances>` has a complete list
  621. of :ref:`methods automatically given to each model <model-instance-methods>`.
  622. You can override most of these -- see `overriding predefined model methods`_,
  623. below -- but there are a couple that you'll almost always want to define:
  624. :meth:`~Model.__str__`
  625. A Python "magic method" that returns a string representation of any
  626. object. This is what Python and Django will use whenever a model
  627. instance needs to be coerced and displayed as a plain string. Most
  628. notably, this happens when you display an object in an interactive
  629. console or in the admin.
  630. You'll always want to define this method; the default isn't very helpful
  631. at all.
  632. :meth:`~Model.get_absolute_url`
  633. This tells Django how to calculate the URL for an object. Django uses
  634. this in its admin interface, and any time it needs to figure out a URL
  635. for an object.
  636. Any object that has a URL that uniquely identifies it should define this
  637. method.
  638. .. _overriding-model-methods:
  639. Overriding predefined model methods
  640. -----------------------------------
  641. There's another set of :ref:`model methods <model-instance-methods>` that
  642. encapsulate a bunch of database behavior that you'll want to customize. In
  643. particular you'll often want to change the way :meth:`~Model.save` and
  644. :meth:`~Model.delete` work.
  645. You're free to override these methods (and any other model method) to alter
  646. behavior.
  647. A classic use-case for overriding the built-in methods is if you want something
  648. to happen whenever you save an object. For example (see
  649. :meth:`~Model.save` for documentation of the parameters it accepts)::
  650. from django.db import models
  651. class Blog(models.Model):
  652. name = models.CharField(max_length=100)
  653. tagline = models.TextField()
  654. def save(self, **kwargs):
  655. do_something()
  656. super().save(**kwargs) # Call the "real" save() method.
  657. do_something_else()
  658. You can also prevent saving::
  659. from django.db import models
  660. class Blog(models.Model):
  661. name = models.CharField(max_length=100)
  662. tagline = models.TextField()
  663. def save(self, **kwargs):
  664. if self.name == "Yoko Ono's blog":
  665. return # Yoko shall never have her own blog!
  666. else:
  667. super().save(**kwargs) # Call the "real" save() method.
  668. It's important to remember to call the superclass method -- that's
  669. that ``super().save(**kwargs)`` business -- to ensure that the object still
  670. gets saved into the database. If you forget to call the superclass method, the
  671. default behavior won't happen and the database won't get touched.
  672. It's also important that you pass through the arguments that can be
  673. passed to the model method -- that's what the ``**kwargs`` bit does. Django
  674. will, from time to time, extend the capabilities of built-in model methods,
  675. adding new keyword arguments. If you use ``**kwargs`` in your method
  676. definitions, you are guaranteed that your code will automatically support those
  677. arguments when they are added.
  678. If you wish to update a field value in the :meth:`~Model.save` method, you may
  679. also want to have this field added to the ``update_fields`` keyword argument.
  680. This will ensure the field is saved when ``update_fields`` is specified. For
  681. example::
  682. from django.db import models
  683. from django.utils.text import slugify
  684. class Blog(models.Model):
  685. name = models.CharField(max_length=100)
  686. slug = models.TextField()
  687. def save(self, **kwargs):
  688. self.slug = slugify(self.name)
  689. if (
  690. update_fields := kwargs.get("update_fields")
  691. ) is not None and "name" in update_fields:
  692. kwargs["update_fields"] = {"slug"}.union(update_fields)
  693. super().save(**kwargs)
  694. See :ref:`ref-models-update-fields` for more details.
  695. .. admonition:: Overridden model methods are not called on bulk operations
  696. Note that the :meth:`~Model.delete()` method for an object is not
  697. necessarily called when :ref:`deleting objects in bulk using a
  698. QuerySet <topics-db-queries-delete>` or as a result of a :attr:`cascading
  699. delete <django.db.models.ForeignKey.on_delete>`. To ensure customized
  700. delete logic gets executed, you can use
  701. :data:`~django.db.models.signals.pre_delete` and/or
  702. :data:`~django.db.models.signals.post_delete` signals.
  703. Unfortunately, there isn't a workaround when
  704. :meth:`creating<django.db.models.query.QuerySet.bulk_create>` or
  705. :meth:`updating<django.db.models.query.QuerySet.update>` objects in bulk,
  706. since none of :meth:`~Model.save()`,
  707. :data:`~django.db.models.signals.pre_save`, and
  708. :data:`~django.db.models.signals.post_save` are called.
  709. Executing custom SQL
  710. --------------------
  711. Another common pattern is writing custom SQL statements in model methods and
  712. module-level methods. For more details on using raw SQL, see the documentation
  713. on :doc:`using raw SQL</topics/db/sql>`.
  714. .. _model-inheritance:
  715. Model inheritance
  716. =================
  717. Model inheritance in Django works almost identically to the way normal
  718. class inheritance works in Python, but the basics at the beginning of the page
  719. should still be followed. That means the base class should subclass
  720. :class:`django.db.models.Model`.
  721. The only decision you have to make is whether you want the parent models to be
  722. models in their own right (with their own database tables), or if the parents
  723. are just holders of common information that will only be visible through the
  724. child models.
  725. There are three styles of inheritance that are possible in Django.
  726. 1. Often, you will just want to use the parent class to hold information that
  727. you don't want to have to type out for each child model. This class isn't
  728. going to ever be used in isolation, so :ref:`abstract-base-classes` are
  729. what you're after.
  730. 2. If you're subclassing an existing model (perhaps something from another
  731. application entirely) and want each model to have its own database table,
  732. :ref:`multi-table-inheritance` is the way to go.
  733. 3. Finally, if you only want to modify the Python-level behavior of a model,
  734. without changing the models fields in any way, you can use
  735. :ref:`proxy-models`.
  736. .. _abstract-base-classes:
  737. Abstract base classes
  738. ---------------------
  739. Abstract base classes are useful when you want to put some common
  740. information into a number of other models. You write your base class
  741. and put ``abstract=True`` in the :ref:`Meta <meta-options>`
  742. class. This model will then not be used to create any database
  743. table. Instead, when it is used as a base class for other models, its
  744. fields will be added to those of the child class.
  745. An example::
  746. from django.db import models
  747. class CommonInfo(models.Model):
  748. name = models.CharField(max_length=100)
  749. age = models.PositiveIntegerField()
  750. class Meta:
  751. abstract = True
  752. class Student(CommonInfo):
  753. home_group = models.CharField(max_length=5)
  754. The ``Student`` model will have three fields: ``name``, ``age`` and
  755. ``home_group``. The ``CommonInfo`` model cannot be used as a normal Django
  756. model, since it is an abstract base class. It does not generate a database
  757. table or have a manager, and cannot be instantiated or saved directly.
  758. Fields inherited from abstract base classes can be overridden with another
  759. field or value, or be removed with ``None``.
  760. For many uses, this type of model inheritance will be exactly what you want.
  761. It provides a way to factor out common information at the Python level, while
  762. still only creating one database table per child model at the database level.
  763. ``Meta`` inheritance
  764. ~~~~~~~~~~~~~~~~~~~~
  765. When an abstract base class is created, Django makes any :ref:`Meta <meta-options>`
  766. inner class you declared in the base class available as an
  767. attribute. If a child class does not declare its own :ref:`Meta <meta-options>`
  768. class, it will inherit the parent's :ref:`Meta <meta-options>`. If the child wants to
  769. extend the parent's :ref:`Meta <meta-options>` class, it can subclass it. For example::
  770. from django.db import models
  771. class CommonInfo(models.Model):
  772. # ...
  773. class Meta:
  774. abstract = True
  775. ordering = ["name"]
  776. class Student(CommonInfo):
  777. # ...
  778. class Meta(CommonInfo.Meta):
  779. db_table = "student_info"
  780. Django does make one adjustment to the :ref:`Meta <meta-options>` class of an
  781. abstract base class: before installing the :ref:`Meta <meta-options>`
  782. attribute, it sets ``abstract=False``. This means that children of abstract
  783. base classes don't automatically become abstract classes themselves. To make
  784. an abstract base class that inherits from another abstract base class, you need
  785. to explicitly set ``abstract=True`` on the child.
  786. Some attributes won't make sense to include in the :ref:`Meta <meta-options>` class of an
  787. abstract base class. For example, including ``db_table`` would mean that all
  788. the child classes (the ones that don't specify their own :ref:`Meta <meta-options>`) would use
  789. the same database table, which is almost certainly not what you want.
  790. Due to the way Python inheritance works, if a child class inherits from
  791. multiple abstract base classes, only the :ref:`Meta <meta-options>` options
  792. from the first listed class will be inherited by default. To inherit :ref:`Meta
  793. <meta-options>` options from multiple abstract base classes, you must
  794. explicitly declare the :ref:`Meta <meta-options>` inheritance. For example::
  795. from django.db import models
  796. class CommonInfo(models.Model):
  797. name = models.CharField(max_length=100)
  798. age = models.PositiveIntegerField()
  799. class Meta:
  800. abstract = True
  801. ordering = ["name"]
  802. class Unmanaged(models.Model):
  803. class Meta:
  804. abstract = True
  805. managed = False
  806. class Student(CommonInfo, Unmanaged):
  807. home_group = models.CharField(max_length=5)
  808. class Meta(CommonInfo.Meta, Unmanaged.Meta):
  809. pass
  810. .. _abstract-related-name:
  811. Be careful with ``related_name`` and ``related_query_name``
  812. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  813. If you are using :attr:`~django.db.models.ForeignKey.related_name` or
  814. :attr:`~django.db.models.ForeignKey.related_query_name` on a ``ForeignKey`` or
  815. ``ManyToManyField``, you must always specify a *unique* reverse name and query
  816. name for the field. This would normally cause a problem in abstract base
  817. classes, since the fields on this class are included into each of the child
  818. classes, with exactly the same values for the attributes (including
  819. :attr:`~django.db.models.ForeignKey.related_name` and
  820. :attr:`~django.db.models.ForeignKey.related_query_name`) each time.
  821. To work around this problem, when you are using
  822. :attr:`~django.db.models.ForeignKey.related_name` or
  823. :attr:`~django.db.models.ForeignKey.related_query_name` in an abstract base
  824. class (only), part of the value should contain ``'%(app_label)s'`` and
  825. ``'%(class)s'``.
  826. - ``'%(class)s'`` is replaced by the lowercased name of the child class that
  827. the field is used in.
  828. - ``'%(app_label)s'`` is replaced by the lowercased name of the app the child
  829. class is contained within. Each installed application name must be unique and
  830. the model class names within each app must also be unique, therefore the
  831. resulting name will end up being different.
  832. For example, given an app ``common/models.py``::
  833. from django.db import models
  834. class Base(models.Model):
  835. m2m = models.ManyToManyField(
  836. OtherModel,
  837. related_name="%(app_label)s_%(class)s_related",
  838. related_query_name="%(app_label)s_%(class)ss",
  839. )
  840. class Meta:
  841. abstract = True
  842. class ChildA(Base):
  843. pass
  844. class ChildB(Base):
  845. pass
  846. Along with another app ``rare/models.py``::
  847. from common.models import Base
  848. class ChildB(Base):
  849. pass
  850. The reverse name of the ``common.ChildA.m2m`` field will be
  851. ``common_childa_related`` and the reverse query name will be ``common_childas``.
  852. The reverse name of the ``common.ChildB.m2m`` field will be
  853. ``common_childb_related`` and the reverse query name will be
  854. ``common_childbs``. Finally, the reverse name of the ``rare.ChildB.m2m`` field
  855. will be ``rare_childb_related`` and the reverse query name will be
  856. ``rare_childbs``. It's up to you how you use the ``'%(class)s'`` and
  857. ``'%(app_label)s'`` portion to construct your related name or related query name
  858. but if you forget to use it, Django will raise errors when you perform system
  859. checks (or run :djadmin:`migrate`).
  860. If you don't specify a :attr:`~django.db.models.ForeignKey.related_name`
  861. attribute for a field in an abstract base class, the default reverse name will
  862. be the name of the child class followed by ``'_set'``, just as it normally
  863. would be if you'd declared the field directly on the child class. For example,
  864. in the above code, if the :attr:`~django.db.models.ForeignKey.related_name`
  865. attribute was omitted, the reverse name for the ``m2m`` field would be
  866. ``childa_set`` in the ``ChildA`` case and ``childb_set`` for the ``ChildB``
  867. field.
  868. .. _multi-table-inheritance:
  869. Multi-table inheritance
  870. -----------------------
  871. The second type of model inheritance supported by Django is when each model in
  872. the hierarchy is a model all by itself. Each model corresponds to its own
  873. database table and can be queried and created individually. The inheritance
  874. relationship introduces links between the child model and each of its parents
  875. (via an automatically-created :class:`~django.db.models.OneToOneField`).
  876. For example::
  877. from django.db import models
  878. class Place(models.Model):
  879. name = models.CharField(max_length=50)
  880. address = models.CharField(max_length=80)
  881. class Restaurant(Place):
  882. serves_hot_dogs = models.BooleanField(default=False)
  883. serves_pizza = models.BooleanField(default=False)
  884. All of the fields of ``Place`` will also be available in ``Restaurant``,
  885. although the data will reside in a different database table. So these are both
  886. possible:
  887. .. code-block:: pycon
  888. >>> Place.objects.filter(name="Bob's Cafe")
  889. >>> Restaurant.objects.filter(name="Bob's Cafe")
  890. If you have a ``Place`` that is also a ``Restaurant``, you can get from the
  891. ``Place`` object to the ``Restaurant`` object by using the lowercase version of
  892. the model name:
  893. .. code-block:: pycon
  894. >>> p = Place.objects.get(id=12)
  895. # If p is a Restaurant object, this will give the child class:
  896. >>> p.restaurant
  897. <Restaurant: ...>
  898. However, if ``p`` in the above example was *not* a ``Restaurant`` (it had been
  899. created directly as a ``Place`` object or was the parent of some other class),
  900. referring to ``p.restaurant`` would raise a ``Restaurant.DoesNotExist``
  901. exception.
  902. The automatically-created :class:`~django.db.models.OneToOneField` on
  903. ``Restaurant`` that links it to ``Place`` looks like this::
  904. place_ptr = models.OneToOneField(
  905. Place,
  906. on_delete=models.CASCADE,
  907. parent_link=True,
  908. primary_key=True,
  909. )
  910. You can override that field by declaring your own
  911. :class:`~django.db.models.OneToOneField` with :attr:`parent_link=True
  912. <django.db.models.OneToOneField.parent_link>` on ``Restaurant``.
  913. .. _meta-and-multi-table-inheritance:
  914. ``Meta`` and multi-table inheritance
  915. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  916. In the multi-table inheritance situation, it doesn't make sense for a child
  917. class to inherit from its parent's :ref:`Meta <meta-options>` class. All the :ref:`Meta <meta-options>` options
  918. have already been applied to the parent class and applying them again would
  919. normally only lead to contradictory behavior (this is in contrast with the
  920. abstract base class case, where the base class doesn't exist in its own
  921. right).
  922. So a child model does not have access to its parent's :ref:`Meta
  923. <meta-options>` class. However, there are a few limited cases where the child
  924. inherits behavior from the parent: if the child does not specify an
  925. :attr:`~django.db.models.Options.ordering` attribute or a
  926. :attr:`~django.db.models.Options.get_latest_by` attribute, it will inherit
  927. these from its parent.
  928. If the parent has an ordering and you don't want the child to have any natural
  929. ordering, you can explicitly disable it::
  930. class ChildModel(ParentModel):
  931. # ...
  932. class Meta:
  933. # Remove parent's ordering effect
  934. ordering = []
  935. Inheritance and reverse relations
  936. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  937. Because multi-table inheritance uses an implicit
  938. :class:`~django.db.models.OneToOneField` to link the child and
  939. the parent, it's possible to move from the parent down to the child,
  940. as in the above example. However, this uses up the name that is the
  941. default :attr:`~django.db.models.ForeignKey.related_name` value for
  942. :class:`~django.db.models.ForeignKey` and
  943. :class:`~django.db.models.ManyToManyField` relations. If you
  944. are putting those types of relations on a subclass of the parent model, you
  945. **must** specify the :attr:`~django.db.models.ForeignKey.related_name`
  946. attribute on each such field. If you forget, Django will raise a validation
  947. error.
  948. For example, using the above ``Place`` class again, let's create another
  949. subclass with a :class:`~django.db.models.ManyToManyField`::
  950. class Supplier(Place):
  951. customers = models.ManyToManyField(Place)
  952. This results in the error:
  953. .. code-block:: pytb
  954. Reverse query name for 'Supplier.customers' clashes with reverse query
  955. name for 'Supplier.place_ptr'.
  956. HINT: Add or change a related_name argument to the definition for
  957. 'Supplier.customers' or 'Supplier.place_ptr'.
  958. Adding ``related_name`` to the ``customers`` field as follows would resolve the
  959. error: ``models.ManyToManyField(Place, related_name='provider')``.
  960. Specifying the parent link field
  961. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  962. As mentioned, Django will automatically create a
  963. :class:`~django.db.models.OneToOneField` linking your child
  964. class back to any non-abstract parent models. If you want to control the
  965. name of the attribute linking back to the parent, you can create your
  966. own :class:`~django.db.models.OneToOneField` and set
  967. :attr:`parent_link=True <django.db.models.OneToOneField.parent_link>`
  968. to indicate that your field is the link back to the parent class.
  969. .. _proxy-models:
  970. Proxy models
  971. ------------
  972. When using :ref:`multi-table inheritance <multi-table-inheritance>`, a new
  973. database table is created for each subclass of a model. This is usually the
  974. desired behavior, since the subclass needs a place to store any additional
  975. data fields that are not present on the base class. Sometimes, however, you
  976. only want to change the Python behavior of a model -- perhaps to change the
  977. default manager, or add a new method.
  978. This is what proxy model inheritance is for: creating a *proxy* for the
  979. original model. You can create, delete and update instances of the proxy model
  980. and all the data will be saved as if you were using the original (non-proxied)
  981. model. The difference is that you can change things like the default model
  982. ordering or the default manager in the proxy, without having to alter the
  983. original.
  984. Proxy models are declared like normal models. You tell Django that it's a
  985. proxy model by setting the :attr:`~django.db.models.Options.proxy` attribute of
  986. the ``Meta`` class to ``True``.
  987. For example, suppose you want to add a method to the ``Person`` model. You can do it like this::
  988. from django.db import models
  989. class Person(models.Model):
  990. first_name = models.CharField(max_length=30)
  991. last_name = models.CharField(max_length=30)
  992. class MyPerson(Person):
  993. class Meta:
  994. proxy = True
  995. def do_something(self):
  996. # ...
  997. pass
  998. The ``MyPerson`` class operates on the same database table as its parent
  999. ``Person`` class. In particular, any new instances of ``Person`` will also be
  1000. accessible through ``MyPerson``, and vice-versa:
  1001. .. code-block:: pycon
  1002. >>> p = Person.objects.create(first_name="foobar")
  1003. >>> MyPerson.objects.get(first_name="foobar")
  1004. <MyPerson: foobar>
  1005. You could also use a proxy model to define a different default ordering on
  1006. a model. You might not always want to order the ``Person`` model, but regularly
  1007. order by the ``last_name`` attribute when you use the proxy::
  1008. class OrderedPerson(Person):
  1009. class Meta:
  1010. ordering = ["last_name"]
  1011. proxy = True
  1012. Now normal ``Person`` queries will be unordered
  1013. and ``OrderedPerson`` queries will be ordered by ``last_name``.
  1014. Proxy models inherit ``Meta`` attributes :ref:`in the same way as regular
  1015. models <meta-and-multi-table-inheritance>`.
  1016. ``QuerySet``\s still return the model that was requested
  1017. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1018. There is no way to have Django return, say, a ``MyPerson`` object whenever you
  1019. query for ``Person`` objects. A queryset for ``Person`` objects will return
  1020. those types of objects. The whole point of proxy objects is that code relying
  1021. on the original ``Person`` will use those and your own code can use the
  1022. extensions you included (that no other code is relying on anyway). It is not
  1023. a way to replace the ``Person`` (or any other) model everywhere with something
  1024. of your own creation.
  1025. Base class restrictions
  1026. ~~~~~~~~~~~~~~~~~~~~~~~
  1027. A proxy model must inherit from exactly one non-abstract model class. You
  1028. can't inherit from multiple non-abstract models as the proxy model doesn't
  1029. provide any connection between the rows in the different database tables. A
  1030. proxy model can inherit from any number of abstract model classes, providing
  1031. they do *not* define any model fields. A proxy model may also inherit from any
  1032. number of proxy models that share a common non-abstract parent class.
  1033. Proxy model managers
  1034. ~~~~~~~~~~~~~~~~~~~~
  1035. If you don't specify any model managers on a proxy model, it inherits the
  1036. managers from its model parents. If you define a manager on the proxy model,
  1037. it will become the default, although any managers defined on the parent
  1038. classes will still be available.
  1039. Continuing our example from above, you could change the default manager used
  1040. when you query the ``Person`` model like this::
  1041. from django.db import models
  1042. class NewManager(models.Manager):
  1043. # ...
  1044. pass
  1045. class MyPerson(Person):
  1046. objects = NewManager()
  1047. class Meta:
  1048. proxy = True
  1049. If you wanted to add a new manager to the Proxy, without replacing the
  1050. existing default, you can use the techniques described in the :ref:`custom
  1051. manager <custom-managers-and-inheritance>` documentation: create a base class
  1052. containing the new managers and inherit that after the primary base class::
  1053. # Create an abstract class for the new manager.
  1054. class ExtraManagers(models.Model):
  1055. secondary = NewManager()
  1056. class Meta:
  1057. abstract = True
  1058. class MyPerson(Person, ExtraManagers):
  1059. class Meta:
  1060. proxy = True
  1061. You probably won't need to do this very often, but, when you do, it's
  1062. possible.
  1063. .. _proxy-vs-unmanaged-models:
  1064. Differences between proxy inheritance and unmanaged models
  1065. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1066. Proxy model inheritance might look fairly similar to creating an unmanaged
  1067. model, using the :attr:`~django.db.models.Options.managed` attribute on a
  1068. model's ``Meta`` class.
  1069. With careful setting of :attr:`Meta.db_table
  1070. <django.db.models.Options.db_table>` you could create an unmanaged model that
  1071. shadows an existing model and adds Python methods to it. However, that would be
  1072. very repetitive and fragile as you need to keep both copies synchronized if you
  1073. make any changes.
  1074. On the other hand, proxy models are intended to behave exactly like the model
  1075. they are proxying for. They are always in sync with the parent model since they
  1076. directly inherit its fields and managers.
  1077. The general rules are:
  1078. #. If you are mirroring an existing model or database table and don't want
  1079. all the original database table columns, use ``Meta.managed=False``.
  1080. That option is normally useful for modeling database views and tables
  1081. not under the control of Django.
  1082. #. If you are wanting to change the Python-only behavior of a model, but
  1083. keep all the same fields as in the original, use ``Meta.proxy=True``.
  1084. This sets things up so that the proxy model is an exact copy of the
  1085. storage structure of the original model when data is saved.
  1086. .. _model-multiple-inheritance-topic:
  1087. Multiple inheritance
  1088. --------------------
  1089. Just as with Python's subclassing, it's possible for a Django model to inherit
  1090. from multiple parent models. Keep in mind that normal Python name resolution
  1091. rules apply. The first base class that a particular name (e.g. :ref:`Meta
  1092. <meta-options>`) appears in will be the one that is used; for example, this
  1093. means that if multiple parents contain a :ref:`Meta <meta-options>` class,
  1094. only the first one is going to be used, and all others will be ignored.
  1095. Generally, you won't need to inherit from multiple parents. The main use-case
  1096. where this is useful is for "mix-in" classes: adding a particular extra
  1097. field or method to every class that inherits the mix-in. Try to keep your
  1098. inheritance hierarchies as simple and straightforward as possible so that you
  1099. won't have to struggle to work out where a particular piece of information is
  1100. coming from.
  1101. Note that inheriting from multiple models that have a common ``id`` primary
  1102. key field will raise an error. To properly use multiple inheritance, you can
  1103. use an explicit :class:`~django.db.models.AutoField` in the base models::
  1104. class Article(models.Model):
  1105. article_id = models.AutoField(primary_key=True)
  1106. ...
  1107. class Book(models.Model):
  1108. book_id = models.AutoField(primary_key=True)
  1109. ...
  1110. class BookReview(Book, Article):
  1111. pass
  1112. Or use a common ancestor to hold the :class:`~django.db.models.AutoField`. This
  1113. requires using an explicit :class:`~django.db.models.OneToOneField` from each
  1114. parent model to the common ancestor to avoid a clash between the fields that
  1115. are automatically generated and inherited by the child::
  1116. class Piece(models.Model):
  1117. pass
  1118. class Article(Piece):
  1119. article_piece = models.OneToOneField(
  1120. Piece, on_delete=models.CASCADE, parent_link=True
  1121. )
  1122. ...
  1123. class Book(Piece):
  1124. book_piece = models.OneToOneField(Piece, on_delete=models.CASCADE, parent_link=True)
  1125. ...
  1126. class BookReview(Book, Article):
  1127. pass
  1128. Field name "hiding" is not permitted
  1129. ------------------------------------
  1130. In normal Python class inheritance, it is permissible for a child class to
  1131. override any attribute from the parent class. In Django, this isn't usually
  1132. permitted for model fields. If a non-abstract model base class has a field
  1133. called ``author``, you can't create another model field or define
  1134. an attribute called ``author`` in any class that inherits from that base class.
  1135. This restriction doesn't apply to model fields inherited from an abstract
  1136. model. Such fields may be overridden with another field or value, or be removed
  1137. by setting ``field_name = None``.
  1138. .. warning::
  1139. Model managers are inherited from abstract base classes. Overriding an
  1140. inherited field which is referenced by an inherited
  1141. :class:`~django.db.models.Manager` may cause subtle bugs. See :ref:`custom
  1142. managers and model inheritance <custom-managers-and-inheritance>`.
  1143. .. note::
  1144. Some fields define extra attributes on the model, e.g. a
  1145. :class:`~django.db.models.ForeignKey` defines an extra attribute with
  1146. ``_id`` appended to the field name, as well as ``related_name`` and
  1147. ``related_query_name`` on the foreign model.
  1148. These extra attributes cannot be overridden unless the field that defines
  1149. it is changed or removed so that it no longer defines the extra attribute.
  1150. Overriding fields in a parent model leads to difficulties in areas such as
  1151. initializing new instances (specifying which field is being initialized in
  1152. ``Model.__init__``) and serialization. These are features which normal Python
  1153. class inheritance doesn't have to deal with in quite the same way, so the
  1154. difference between Django model inheritance and Python class inheritance isn't
  1155. arbitrary.
  1156. This restriction only applies to attributes which are
  1157. :class:`~django.db.models.Field` instances. Normal Python attributes
  1158. can be overridden if you wish. It also only applies to the name of the
  1159. attribute as Python sees it: if you are manually specifying the database
  1160. column name, you can have the same column name appearing in both a child and
  1161. an ancestor model for multi-table inheritance (they are columns in two
  1162. different database tables).
  1163. Django will raise a :exc:`~django.core.exceptions.FieldError` if you override
  1164. any model field in any ancestor model.
  1165. Note that because of the way fields are resolved during class definition, model
  1166. fields inherited from multiple abstract parent models are resolved in a strict
  1167. depth-first order. This contrasts with standard Python MRO, which is resolved
  1168. breadth-first in cases of diamond shaped inheritance. This difference only
  1169. affects complex model hierarchies, which (as per the advice above) you should
  1170. try to avoid.
  1171. Organizing models in a package
  1172. ==============================
  1173. The :djadmin:`manage.py startapp <startapp>` command creates an application
  1174. structure that includes a ``models.py`` file. If you have many models,
  1175. organizing them in separate files may be useful.
  1176. To do so, create a ``models`` package. Remove ``models.py`` and create a
  1177. ``myapp/models/`` directory with an ``__init__.py`` file and the files to
  1178. store your models. You must import the models in the ``__init__.py`` file.
  1179. For example, if you had ``organic.py`` and ``synthetic.py`` in the ``models``
  1180. directory:
  1181. .. code-block:: python
  1182. :caption: ``myapp/models/__init__.py``
  1183. from .organic import Person
  1184. from .synthetic import Robot
  1185. Explicitly importing each model rather than using ``from .models import *``
  1186. has the advantages of not cluttering the namespace, making code more readable,
  1187. and keeping code analysis tools useful.
  1188. .. seealso::
  1189. :doc:`The Models Reference </ref/models/index>`
  1190. Covers all the model related APIs including model fields, related
  1191. objects, and ``QuerySet``.