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