models.txt 59 KB

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