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