1. ======================
    
  2. Model ``Meta`` options
    
  3. ======================
    
  4. 
    
  5. This document explains all the possible :ref:`metadata options
    
  6. <meta-options>` that you can give your model in its internal
    
  7. ``class Meta``.
    
  8. 
    
  9. Available ``Meta`` options
    
  10. ==========================
    
  11. 
    
  12. .. currentmodule:: django.db.models
    
  13. 
    
  14. ``abstract``
    
  15. ------------
    
  16. 
    
  17. .. attribute:: Options.abstract
    
  18. 
    
  19.     If ``abstract = True``, this model will be an
    
  20.     :ref:`abstract base class <abstract-base-classes>`.
    
  21. 
    
  22. ``app_label``
    
  23. -------------
    
  24. 
    
  25. .. attribute:: Options.app_label
    
  26. 
    
  27.     If a model is defined outside of an application in
    
  28.     :setting:`INSTALLED_APPS`, it must declare which app it belongs to::
    
  29. 
    
  30.         app_label = 'myapp'
    
  31. 
    
  32.     If you want to represent a model with the format ``app_label.object_name``
    
  33.     or ``app_label.model_name`` you can use ``model._meta.label``
    
  34.     or ``model._meta.label_lower`` respectively.
    
  35. 
    
  36. ``base_manager_name``
    
  37. ---------------------
    
  38. 
    
  39. .. attribute:: Options.base_manager_name
    
  40. 
    
  41.     The attribute name of the manager, for example, ``'objects'``, to use for
    
  42.     the model's :attr:`~django.db.models.Model._base_manager`.
    
  43. 
    
  44. ``db_table``
    
  45. ------------
    
  46. 
    
  47. .. attribute:: Options.db_table
    
  48. 
    
  49.     The name of the database table to use for the model::
    
  50. 
    
  51.         db_table = 'music_album'
    
  52. 
    
  53. .. _table-names:
    
  54. 
    
  55. Table names
    
  56. ~~~~~~~~~~~
    
  57. 
    
  58. To save you time, Django automatically derives the name of the database table
    
  59. from the name of your model class and the app that contains it. A model's
    
  60. database table name is constructed by joining the model's "app label" -- the
    
  61. name you used in :djadmin:`manage.py startapp <startapp>` -- to the model's
    
  62. class name, with an underscore between them.
    
  63. 
    
  64. For example, if you have an app ``bookstore`` (as created by
    
  65. ``manage.py startapp bookstore``), a model defined as ``class Book`` will have
    
  66. a database table named ``bookstore_book``.
    
  67. 
    
  68. To override the database table name, use the ``db_table`` parameter in
    
  69. ``class Meta``.
    
  70. 
    
  71. If your database table name is an SQL reserved word, or contains characters that
    
  72. aren't allowed in Python variable names -- notably, the hyphen -- that's OK.
    
  73. Django quotes column and table names behind the scenes.
    
  74. 
    
  75. .. admonition:: Use lowercase table names for MariaDB and MySQL
    
  76. 
    
  77.     It is strongly advised that you use lowercase table names when you override
    
  78.     the table name via ``db_table``, particularly if you are using the MySQL
    
  79.     backend. See the :ref:`MySQL notes <mysql-notes>` for more details.
    
  80. 
    
  81. .. admonition:: Table name quoting for Oracle
    
  82. 
    
  83.    In order to meet the 30-char limitation Oracle has on table names,
    
  84.    and match the usual conventions for Oracle databases, Django may shorten
    
  85.    table names and turn them all-uppercase. To prevent such transformations,
    
  86.    use a quoted name as the value for ``db_table``::
    
  87. 
    
  88.        db_table = '"name_left_in_lowercase"'
    
  89. 
    
  90.    Such quoted names can also be used with Django's other supported database
    
  91.    backends; except for Oracle, however, the quotes have no effect. See the
    
  92.    :ref:`Oracle notes <oracle-notes>` for more details.
    
  93. 
    
  94. ``db_tablespace``
    
  95. -----------------
    
  96. 
    
  97. .. attribute:: Options.db_tablespace
    
  98. 
    
  99.     The name of the :doc:`database tablespace </topics/db/tablespaces>` to use
    
  100.     for this model. The default is the project's :setting:`DEFAULT_TABLESPACE`
    
  101.     setting, if set. If the backend doesn't support tablespaces, this option is
    
  102.     ignored.
    
  103. 
    
  104. ``default_manager_name``
    
  105. ------------------------
    
  106. 
    
  107. .. attribute:: Options.default_manager_name
    
  108. 
    
  109.     The name of the manager to use for the model's
    
  110.     :attr:`~django.db.models.Model._default_manager`.
    
  111. 
    
  112. ``default_related_name``
    
  113. ------------------------
    
  114. 
    
  115. .. attribute:: Options.default_related_name
    
  116. 
    
  117.     The name that will be used by default for the relation from a related object
    
  118.     back to this one. The default is ``<model_name>_set``.
    
  119. 
    
  120.     This option also sets :attr:`~ForeignKey.related_query_name`.
    
  121. 
    
  122.     As the reverse name for a field should be unique, be careful if you intend
    
  123.     to subclass your model. To work around name collisions, part of the name
    
  124.     should contain ``'%(app_label)s'`` and ``'%(model_name)s'``, which are
    
  125.     replaced respectively by the name of the application the model is in,
    
  126.     and the name of the model, both lowercased. See the paragraph on
    
  127.     :ref:`related names for abstract models <abstract-related-name>`.
    
  128. 
    
  129. ``get_latest_by``
    
  130. -----------------
    
  131. 
    
  132. .. attribute:: Options.get_latest_by
    
  133. 
    
  134.     The name of a field or a list of field names in the model, typically
    
  135.     :class:`DateField`, :class:`DateTimeField`, or :class:`IntegerField`. This
    
  136.     specifies the default field(s) to use in your model :class:`Manager`’s
    
  137.     :meth:`~django.db.models.query.QuerySet.latest` and
    
  138.     :meth:`~django.db.models.query.QuerySet.earliest` methods.
    
  139. 
    
  140.     Example::
    
  141. 
    
  142.         # Latest by ascending order_date.
    
  143.         get_latest_by = "order_date"
    
  144. 
    
  145.         # Latest by priority descending, order_date ascending.
    
  146.         get_latest_by = ['-priority', 'order_date']
    
  147. 
    
  148.     See the :meth:`~django.db.models.query.QuerySet.latest` docs for more.
    
  149. 
    
  150. ``managed``
    
  151. -----------
    
  152. 
    
  153. .. attribute:: Options.managed
    
  154. 
    
  155.     Defaults to ``True``, meaning Django will create the appropriate database
    
  156.     tables in :djadmin:`migrate` or as part of migrations and remove them as
    
  157.     part of a :djadmin:`flush` management command. That is, Django
    
  158.     *manages* the database tables' lifecycles.
    
  159. 
    
  160.     If ``False``, no database table creation, modification, or deletion
    
  161.     operations will be performed for this model. This is useful if the model
    
  162.     represents an existing table or a database view that has been created by
    
  163.     some other means. This is the *only* difference when ``managed=False``. All
    
  164.     other aspects of model handling are exactly the same as normal. This
    
  165.     includes
    
  166. 
    
  167.     #. Adding an automatic primary key field to the model if you don't
    
  168.        declare it.  To avoid confusion for later code readers, it's
    
  169.        recommended to specify all the columns from the database table you
    
  170.        are modeling when using unmanaged models.
    
  171. 
    
  172.     #. If a model with ``managed=False`` contains a
    
  173.        :class:`~django.db.models.ManyToManyField` that points to another
    
  174.        unmanaged model, then the intermediate table for the many-to-many
    
  175.        join will also not be created. However, the intermediary table
    
  176.        between one managed and one unmanaged model *will* be created.
    
  177. 
    
  178.        If you need to change this default behavior, create the intermediary
    
  179.        table as an explicit model (with ``managed`` set as needed) and use
    
  180.        the :attr:`ManyToManyField.through` attribute to make the relation
    
  181.        use your custom model.
    
  182. 
    
  183.     For tests involving models with ``managed=False``, it's up to you to ensure
    
  184.     the correct tables are created as part of the test setup.
    
  185. 
    
  186.     If you're interested in changing the Python-level behavior of a model class,
    
  187.     you *could* use ``managed=False`` and create a copy of an existing model.
    
  188.     However, there's a better approach for that situation: :ref:`proxy-models`.
    
  189. 
    
  190. ``order_with_respect_to``
    
  191. -------------------------
    
  192. 
    
  193. .. attribute:: Options.order_with_respect_to
    
  194. 
    
  195.     Makes this object orderable with respect to the given field, usually a
    
  196.     ``ForeignKey``. This can be used to make related objects orderable with
    
  197.     respect to a parent object. For example, if an ``Answer`` relates to a
    
  198.     ``Question`` object, and a question has more than one answer, and the order
    
  199.     of answers matters, you'd do this::
    
  200. 
    
  201.         from django.db import models
    
  202. 
    
  203.         class Question(models.Model):
    
  204.             text = models.TextField()
    
  205.             # ...
    
  206. 
    
  207.         class Answer(models.Model):
    
  208.             question = models.ForeignKey(Question, on_delete=models.CASCADE)
    
  209.             # ...
    
  210. 
    
  211.             class Meta:
    
  212.                 order_with_respect_to = 'question'
    
  213. 
    
  214.     When ``order_with_respect_to`` is set, two additional methods are provided to
    
  215.     retrieve and to set the order of the related objects: ``get_RELATED_order()``
    
  216.     and ``set_RELATED_order()``, where ``RELATED`` is the lowercased model name. For
    
  217.     example, assuming that a ``Question`` object has multiple related ``Answer``
    
  218.     objects, the list returned contains the primary keys of the related ``Answer``
    
  219.     objects::
    
  220. 
    
  221.         >>> question = Question.objects.get(id=1)
    
  222.         >>> question.get_answer_order()
    
  223.         [1, 2, 3]
    
  224. 
    
  225.     The order of a ``Question`` object's related ``Answer`` objects can be set by
    
  226.     passing in a list of ``Answer`` primary keys::
    
  227. 
    
  228.         >>> question.set_answer_order([3, 1, 2])
    
  229. 
    
  230.     The related objects also get two methods, ``get_next_in_order()`` and
    
  231.     ``get_previous_in_order()``, which can be used to access those objects in their
    
  232.     proper order. Assuming the ``Answer`` objects are ordered by ``id``::
    
  233. 
    
  234.         >>> answer = Answer.objects.get(id=2)
    
  235.         >>> answer.get_next_in_order()
    
  236.         <Answer: 3>
    
  237.         >>> answer.get_previous_in_order()
    
  238.         <Answer: 1>
    
  239. 
    
  240. .. admonition:: ``order_with_respect_to`` implicitly sets the ``ordering`` option
    
  241. 
    
  242.     Internally, ``order_with_respect_to`` adds an additional field/database
    
  243.     column named ``_order`` and sets the model's :attr:`~Options.ordering`
    
  244.     option to this field. Consequently, ``order_with_respect_to`` and
    
  245.     ``ordering`` cannot be used together, and the ordering added by
    
  246.     ``order_with_respect_to`` will apply whenever you obtain a list of objects
    
  247.     of this model.
    
  248. 
    
  249. .. admonition:: Changing ``order_with_respect_to``
    
  250. 
    
  251.     Because ``order_with_respect_to`` adds a new database column, be sure to
    
  252.     make and apply the appropriate migrations if you add or change
    
  253.     ``order_with_respect_to`` after your initial :djadmin:`migrate`.
    
  254. 
    
  255. ``ordering``
    
  256. ------------
    
  257. 
    
  258. .. attribute:: Options.ordering
    
  259. 
    
  260.     The default ordering for the object, for use when obtaining lists of objects::
    
  261. 
    
  262.         ordering = ['-order_date']
    
  263. 
    
  264.     This is a tuple or list of strings and/or query expressions. Each string is
    
  265.     a field name with an optional "-" prefix, which indicates descending order.
    
  266.     Fields without a leading "-" will be ordered ascending. Use the string "?"
    
  267.     to order randomly.
    
  268. 
    
  269.     For example, to order by a ``pub_date`` field ascending, use this::
    
  270. 
    
  271.         ordering = ['pub_date']
    
  272. 
    
  273.     To order by ``pub_date`` descending, use this::
    
  274. 
    
  275.         ordering = ['-pub_date']
    
  276. 
    
  277.     To order by ``pub_date`` descending, then by ``author`` ascending, use this::
    
  278. 
    
  279.         ordering = ['-pub_date', 'author']
    
  280. 
    
  281.     You can also use :doc:`query expressions </ref/models/expressions>`. To
    
  282.     order by ``author`` ascending and make null values sort last, use this::
    
  283. 
    
  284.         from django.db.models import F
    
  285. 
    
  286.         ordering = [F('author').asc(nulls_last=True)]
    
  287. 
    
  288. .. warning::
    
  289. 
    
  290.     Ordering is not a free operation. Each field you add to the ordering
    
  291.     incurs a cost to your database. Each foreign key you add will
    
  292.     implicitly include all of its default orderings as well.
    
  293. 
    
  294.     If a query doesn't have an ordering specified, results are returned from
    
  295.     the database in an unspecified order. A particular ordering is guaranteed
    
  296.     only when ordering by a set of fields that uniquely identify each object in
    
  297.     the results. For example, if a ``name`` field isn't unique, ordering by it
    
  298.     won't guarantee objects with the same name always appear in the same order.
    
  299. 
    
  300. ``permissions``
    
  301. ---------------
    
  302. 
    
  303. .. attribute:: Options.permissions
    
  304. 
    
  305.     Extra permissions to enter into the permissions table when creating this object.
    
  306.     Add, change, delete, and view permissions are automatically created for each
    
  307.     model. This example specifies an extra permission, ``can_deliver_pizzas``::
    
  308. 
    
  309.         permissions = [('can_deliver_pizzas', 'Can deliver pizzas')]
    
  310. 
    
  311.     This is a list or tuple of 2-tuples in the format ``(permission_code,
    
  312.     human_readable_permission_name)``.
    
  313. 
    
  314. ``default_permissions``
    
  315. -----------------------
    
  316. 
    
  317. .. attribute:: Options.default_permissions
    
  318. 
    
  319.     Defaults to ``('add', 'change', 'delete', 'view')``. You may customize this
    
  320.     list, for example, by setting this to an empty list if your app doesn't
    
  321.     require any of the default permissions. It must be specified on the model
    
  322.     before the model is created by :djadmin:`migrate` in order to prevent any
    
  323.     omitted permissions from being created.
    
  324. 
    
  325. ``proxy``
    
  326. ---------
    
  327. 
    
  328. .. attribute:: Options.proxy
    
  329. 
    
  330.     If ``proxy = True``, a model which subclasses another model will be treated as
    
  331.     a :ref:`proxy model <proxy-models>`.
    
  332. 
    
  333. ``required_db_features``
    
  334. ------------------------
    
  335. 
    
  336. .. attribute:: Options.required_db_features
    
  337. 
    
  338.     List of database features that the current connection should have so that
    
  339.     the model is considered during the migration phase. For example, if you set
    
  340.     this list to ``['gis_enabled']``, the model will only be synchronized on
    
  341.     GIS-enabled databases. It's also useful to skip some models when testing
    
  342.     with several database backends. Avoid relations between models that may or
    
  343.     may not be created as the ORM doesn't handle this.
    
  344. 
    
  345. ``required_db_vendor``
    
  346. ----------------------
    
  347. 
    
  348. .. attribute:: Options.required_db_vendor
    
  349. 
    
  350.     Name of a supported database vendor that this model is specific to. Current
    
  351.     built-in vendor names are: ``sqlite``, ``postgresql``, ``mysql``,
    
  352.     ``oracle``. If this attribute is not empty and the current connection vendor
    
  353.     doesn't match it, the model will not be synchronized.
    
  354. 
    
  355. ``select_on_save``
    
  356. ------------------
    
  357. 
    
  358. .. attribute:: Options.select_on_save
    
  359. 
    
  360.     Determines if Django will use the pre-1.6
    
  361.     :meth:`django.db.models.Model.save()` algorithm. The old algorithm
    
  362.     uses ``SELECT`` to determine if there is an existing row to be updated.
    
  363.     The new algorithm tries an ``UPDATE`` directly. In some rare cases the
    
  364.     ``UPDATE`` of an existing row isn't visible to Django. An example is the
    
  365.     PostgreSQL ``ON UPDATE`` trigger which returns ``NULL``. In such cases the
    
  366.     new algorithm will end up doing an ``INSERT`` even when a row exists in
    
  367.     the database.
    
  368. 
    
  369.     Usually there is no need to set this attribute. The default is
    
  370.     ``False``.
    
  371. 
    
  372.     See :meth:`django.db.models.Model.save()` for more about the old and
    
  373.     new saving algorithm.
    
  374. 
    
  375. ``indexes``
    
  376. -----------
    
  377. 
    
  378. .. attribute:: Options.indexes
    
  379. 
    
  380.     A list of :doc:`indexes </ref/models/indexes>` that you want to define on
    
  381.     the model::
    
  382. 
    
  383.         from django.db import models
    
  384. 
    
  385.         class Customer(models.Model):
    
  386.             first_name = models.CharField(max_length=100)
    
  387.             last_name = models.CharField(max_length=100)
    
  388. 
    
  389.             class Meta:
    
  390.                 indexes = [
    
  391.                     models.Index(fields=['last_name', 'first_name']),
    
  392.                     models.Index(fields=['first_name'], name='first_name_idx'),
    
  393.                 ]
    
  394. 
    
  395. ``unique_together``
    
  396. -------------------
    
  397. 
    
  398. .. attribute:: Options.unique_together
    
  399. 
    
  400.     .. admonition:: Use :class:`.UniqueConstraint` with the :attr:`~Options.constraints` option instead.
    
  401. 
    
  402.         :class:`.UniqueConstraint` provides more functionality than
    
  403.         ``unique_together``. ``unique_together`` may be deprecated in the
    
  404.         future.
    
  405. 
    
  406.     Sets of field names that, taken together, must be unique::
    
  407. 
    
  408.         unique_together = [['driver', 'restaurant']]
    
  409. 
    
  410.     This is a list of lists that must be unique when considered together.
    
  411.     It's used in the Django admin and is enforced at the database level (i.e., the
    
  412.     appropriate ``UNIQUE`` statements are included in the ``CREATE TABLE``
    
  413.     statement).
    
  414. 
    
  415.     For convenience, ``unique_together`` can be a single list when dealing with
    
  416.     a single set of fields::
    
  417. 
    
  418.         unique_together = ['driver', 'restaurant']
    
  419. 
    
  420.     A :class:`~django.db.models.ManyToManyField` cannot be included in
    
  421.     unique_together. (It's not clear what that would even mean!) If you
    
  422.     need to validate uniqueness related to a
    
  423.     :class:`~django.db.models.ManyToManyField`, try using a signal or
    
  424.     an explicit :attr:`through <ManyToManyField.through>` model.
    
  425. 
    
  426.     The ``ValidationError`` raised during model validation when the constraint
    
  427.     is violated has the ``unique_together`` error code.
    
  428. 
    
  429. ``index_together``
    
  430. ------------------
    
  431. 
    
  432. .. attribute:: Options.index_together
    
  433. 
    
  434.     .. admonition:: Use the :attr:`~Options.indexes` option instead.
    
  435. 
    
  436.         The newer :attr:`~Options.indexes` option provides more functionality
    
  437.         than ``index_together``. ``index_together`` may be deprecated in the
    
  438.         future.
    
  439. 
    
  440.     Sets of field names that, taken together, are indexed::
    
  441. 
    
  442.         index_together = [
    
  443.             ["pub_date", "deadline"],
    
  444.         ]
    
  445. 
    
  446.     This list of fields will be indexed together (i.e. the appropriate
    
  447.     ``CREATE INDEX`` statement will be issued.)
    
  448. 
    
  449.     For convenience, ``index_together`` can be a single list when dealing with a single
    
  450.     set of fields::
    
  451. 
    
  452.         index_together = ["pub_date", "deadline"]
    
  453. 
    
  454. ``constraints``
    
  455. ---------------
    
  456. 
    
  457. .. attribute:: Options.constraints
    
  458. 
    
  459.     A list of :doc:`constraints </ref/models/constraints>` that you want to
    
  460.     define on the model::
    
  461. 
    
  462.         from django.db import models
    
  463. 
    
  464.         class Customer(models.Model):
    
  465.             age = models.IntegerField()
    
  466. 
    
  467.             class Meta:
    
  468.                 constraints = [
    
  469.                     models.CheckConstraint(check=models.Q(age__gte=18), name='age_gte_18'),
    
  470.                 ]
    
  471. 
    
  472. ``verbose_name``
    
  473. ----------------
    
  474. 
    
  475. .. attribute:: Options.verbose_name
    
  476. 
    
  477.     A human-readable name for the object, singular::
    
  478. 
    
  479.         verbose_name = "pizza"
    
  480. 
    
  481.     If this isn't given, Django will use a munged version of the class name:
    
  482.     ``CamelCase`` becomes ``camel case``.
    
  483. 
    
  484. ``verbose_name_plural``
    
  485. -----------------------
    
  486. 
    
  487. .. attribute:: Options.verbose_name_plural
    
  488. 
    
  489.     The plural name for the object::
    
  490. 
    
  491.         verbose_name_plural = "stories"
    
  492. 
    
  493.     If this isn't given, Django will use :attr:`~Options.verbose_name` + ``"s"``.
    
  494. 
    
  495. Read-only ``Meta`` attributes
    
  496. =============================
    
  497. 
    
  498. ``label``
    
  499. ---------
    
  500. 
    
  501. .. attribute:: Options.label
    
  502. 
    
  503.     Representation of the object, returns ``app_label.object_name``, e.g.
    
  504.     ``'polls.Question'``.
    
  505. 
    
  506. ``label_lower``
    
  507. ---------------
    
  508. 
    
  509. .. attribute:: Options.label_lower
    
  510. 
    
  511.     Representation of the model, returns ``app_label.model_name``, e.g.
    
  512.     ``'polls.question'``.