- Model Meta options
- Available Meta options
- abstract
- app_label
- base_manager_name
- db_table
- db_tablespace
- default_manager_name
- default_related_name
- get_latest_by
- managed
- order_with_respect_to
- ordering
- permissions
- default_permissions
- proxy
- required_db_features
- required_db_vendor
- select_on_save
- indexes
- unique_together
- index_together
- constraints
- verbose_name
- verbose_name_plural
- Read-only Meta attributes
- Available Meta options
Model Meta options
This document explains all the possible metadata options that you can give your model in its internalclass Meta
.
Available Meta options
abstract
Options.
abstract
- If
abstract = True
, this model will be anabstract base class.
app_label
Options.
app_label
- If a model is defined outside of an application in
INSTALLED_APPS
, it must declare which app it belongs to:
- app_label = 'myapp'
If you want to represent a model with the format app_label.object_name
or app_label.model_name
you can use model._meta.label
or model._meta.label_lower
respectively.
base_manager_name
Options.
base_manager_name
- The attribute name of the manager, for example,
'objects'
, to use forthe model's_base_manager
.
db_table
- db_table = 'music_album'
Table names
To save you time, Django automatically derives the name of the database tablefrom the name of your model class and the app that contains it. A model'sdatabase table name is constructed by joining the model's "app label" — thename you used in manage.py startapp
— to the model'sclass name, with an underscore between them.
For example, if you have an app bookstore
(as created bymanage.py startapp bookstore
), a model defined as class Book
will havea database table named bookstore_book
.
To override the database table name, use the db_table
parameter inclass Meta
.
If your database table name is an SQL reserved word, or contains characters thataren't allowed in Python variable names — notably, the hyphen — that's OK.Django quotes column and table names behind the scenes.
Use lowercase table names for MySQL
It is strongly advised that you use lowercase table names when you overridethe table name via db_table
, particularly if you are using the MySQLbackend. See the MySQL notes for more details.
Table name quoting for Oracle
In order to meet the 30-char limitation Oracle has on table names,and match the usual conventions for Oracle databases, Django may shortentable names and turn them all-uppercase. To prevent such transformations,use a quoted name as the value for db_table
:
- db_table = '"name_left_in_lowercase"'
Such quoted names can also be used with Django's other supported databasebackends; except for Oracle, however, the quotes have no effect. See theOracle notes for more details.
db_tablespace
Options.
db_tablespace
- The name of the database tablespace to usefor this model. The default is the project's
DEFAULT_TABLESPACE
setting, if set. If the backend doesn't support tablespaces, this option isignored.
default_manager_name
Options.
default_manager_name
- The name of the manager to use for the model's
_default_manager
.
default_related_name
Options.
default_related_name
- The name that will be used by default for the relation from a related objectback to this one. The default is
<model_name>_set
.
This option also sets related_query_name
.
As the reverse name for a field should be unique, be careful if you intendto subclass your model. To work around name collisions, part of the nameshould contain '%(app_label)s'
and '%(model_name)s'
, which arereplaced respectively by the name of the application the model is in,and the name of the model, both lowercased. See the paragraph onrelated names for abstract models.
get_latest_by
Options.
get_latest_by
- The name of a field or a list of field names in the model, typically
DateField
,DateTimeField
, orIntegerField
. Thisspecifies the default field(s) to use in your modelManager
’slatest()
andearliest()
methods.
举例:
- # Latest by ascending order_date.
- get_latest_by = "order_date"
- # Latest by priority descending, order_date ascending.
- get_latest_by = ['-priority', 'order_date']
See the latest()
docs for more.
managed
Options.
managed
- Defaults to
True
, meaning Django will create the appropriate databasetables inmigrate
or as part of migrations and remove them aspart of aflush
management command. That is, Djangomanages the database tables' lifecycles.
If False
, no database table creation or deletion operations will beperformed for this model. This is useful if the model represents an existingtable or a database view that has been created by some other means. This isthe only difference when managed=False
. All other aspects ofmodel handling are exactly the same as normal. This includes
Adding an automatic primary key field to the model if you don'tdeclare it. To avoid confusion for later code readers, it'srecommended to specify all the columns from the database table youare modeling when using unmanaged models.
If a model with
managed=False
contains aManyToManyField
that points to anotherunmanaged model, then the intermediate table for the many-to-manyjoin will also not be created. However, the intermediary tablebetween one managed and one unmanaged model will be created.
If you need to change this default behavior, create the intermediarytable as an explicit model (with managed
set as needed) and usethe ManyToManyField.through
attribute to make the relationuse your custom model.
For tests involving models with managed=False
, it's up to you to ensurethe correct tables are created as part of the test setup.
If you're interested in changing the Python-level behavior of a model class,you could use managed=False
and create a copy of an existing model.However, there's a better approach for that situation: 代理模型.
order_with_respect_to
Options.
order_with_respect_to
- Makes this object orderable with respect to the given field, usually a
ForeignKey
. This can be used to make related objects orderable withrespect to a parent object. For example, if anAnswer
relates to aQuestion
object, and a question has more than one answer, and the orderof answers matters, you'd do this:
- from django.db import models
- class Question(models.Model):
- text = models.TextField()
- # ...
- class Answer(models.Model):
- question = models.ForeignKey(Question, on_delete=models.CASCADE)
- # ...
- class Meta:
- order_with_respect_to = 'question'
When order_with_respect_to
is set, two additional methods are provided toretrieve and to set the order of the related objects: get_RELATED_order()
and set_RELATED_order()
, where RELATED
is the lowercased model name. Forexample, assuming that a Question
object has multiple related Answer
objects, the list returned contains the primary keys of the related Answer
objects:
- >>> question = Question.objects.get(id=1)
- >>> question.get_answer_order()
- [1, 2, 3]
The order of a Question
object's related Answer
objects can be set bypassing in a list of Answer
primary keys:
- >>> question.set_answer_order([3, 1, 2])
The related objects also get two methods, get_next_in_order()
andget_previous_in_order()
, which can be used to access those objects in theirproper order. Assuming the Answer
objects are ordered by id
:
- >>> answer = Answer.objects.get(id=2)
- >>> answer.get_next_in_order()
- <Answer: 3>
- >>> answer.get_previous_in_order()
- <Answer: 1>
order_with_respect_to
implicitly sets the ordering
option
Internally, order_with_respect_to
adds an additional field/databasecolumn named _order
and sets the model's ordering
option to this field. Consequently, order_with_respect_to
andordering
cannot be used together, and the ordering added byorder_with_respect_to
will apply whenever you obtain a list of objectsof this model.
Changing order_with_respect_to
Because order_with_respect_to
adds a new database column, be sure tomake and apply the appropriate migrations if you add or changeorder_with_respect_to
after your initial migrate
.
ordering
- ordering = ['-order_date']
This is a tuple or list of strings and/or query expressions. Each string isa field name with an optional "-" prefix, which indicates descending order.Fields without a leading "-" will be ordered ascending. Use the string "?"to order randomly.
For example, to order by a pub_date
field ascending, use this:
- ordering = ['pub_date']
To order by pub_date
descending, use this:
- ordering = ['-pub_date']
To order by pub_date
descending, then by author
ascending, use this:
- ordering = ['-pub_date', 'author']
You can also use query expressions. Toorder by author
ascending and make null values sort last, use this:
- from django.db.models import F
- ordering = [F('author').asc(nulls_last=True)]
Default ordering also affects aggregation queries but this won't be the case startingin Django 3.1.
警告
Ordering is not a free operation. Each field you add to the orderingincurs a cost to your database. Each foreign key you add willimplicitly include all of its default orderings as well.
If a query doesn't have an ordering specified, results are returned fromthe database in an unspecified order. A particular ordering is guaranteedonly when ordering by a set of fields that uniquely identify each object inthe results. For example, if a name
field isn't unique, ordering by itwon't guarantee objects with the same name always appear in the same order.
permissions
Options.
permissions
- Extra permissions to enter into the permissions table when creating this object.Add, change, delete, and view permissions are automatically created for eachmodel. This example specifies an extra permission,
can_deliver_pizzas
:
- permissions = [('can_deliver_pizzas', 'Can deliver pizzas')]
This is a list or tuple of 2-tuples in the format (permission_code,human_readable_permission_name)
.
default_permissions
Options.
default_permissions
- Defaults to
('add', 'change', 'delete', 'view')
. You may customize thislist, for example, by setting this to an empty list if your app doesn'trequire any of the default permissions. It must be specified on the modelbefore the model is created bymigrate
in order to prevent anyomitted permissions from being created.
Changed in Django 2.1:The view
permission was added.
proxy
Options.
proxy
- If
proxy = True
, a model which subclasses another model will be treated asa proxy model.
required_db_features
Options.
required_db_features
- List of database features that the current connection should have so thatthe model is considered during the migration phase. For example, if you setthis list to
['gis_enabled']
, the model will only be synchronized onGIS-enabled databases. It's also useful to skip some models when testingwith several database backends. Avoid relations between models that may ormay not be created as the ORM doesn't handle this.
required_db_vendor
Options.
required_db_vendor
- Name of a supported database vendor that this model is specific to. Currentbuilt-in vendor names are:
sqlite
,postgresql
,mysql
,oracle
. If this attribute is not empty and the current connection vendordoesn't match it, the model will not be synchronized.
select_on_save
Options.
select_on_save
- Determines if Django will use the pre-1.6
django.db.models.Model.save()
algorithm. The old algorithmusesSELECT
to determine if there is an existing row to be updated.The new algorithm tries anUPDATE
directly. In some rare cases theUPDATE
of an existing row isn't visible to Django. An example is thePostgreSQLON UPDATE
trigger which returnsNULL
. In such cases thenew algorithm will end up doing anINSERT
even when a row exists inthe database.
Usually there is no need to set this attribute. The default isFalse
.
See django.db.models.Model.save()
for more about the old andnew saving algorithm.
indexes
Options.
indexes
- A list of indexes that you want to define onthe model:
- from django.db import models
- class Customer(models.Model):
- first_name = models.CharField(max_length=100)
- last_name = models.CharField(max_length=100)
- class Meta:
- indexes = [
- models.Index(fields=['last_name', 'first_name']),
- models.Index(fields=['first_name'], name='first_name_idx'),
- ]
unique_together
Use UniqueConstraint
with the constraints
option instead.
UniqueConstraint
provides more functionality thanunique_together
. unique_together
may be deprecated in thefuture.
Sets of field names that, taken together, must be unique:
- unique_together = [['driver', 'restaurant']]
This is a list of lists that must be unique when considered together.It's used in the Django admin and is enforced at the database level (i.e., theappropriate UNIQUE
statements are included in the CREATE TABLE
statement).
For convenience, unique_together
can be a single list when dealing witha single set of fields:
- unique_together = ['driver', 'restaurant']
A ManyToManyField
cannot be included inunique_together. (It's not clear what that would even mean!) If youneed to validate uniqueness related to aManyToManyField
, try using a signal oran explicit through
model.
The ValidationError
raised during model validation when the constraintis violated has the unique_together
error code.
index_together
Use the indexes
option instead.
The newer indexes
option provides more functionalitythan index_together
. index_together
may be deprecated in thefuture.
Sets of field names that, taken together, are indexed:
- index_together = [
- ["pub_date", "deadline"],
- ]
This list of fields will be indexed together (i.e. the appropriateCREATE INDEX
statement will be issued.)
For convenience, index_together
can be a single list when dealing with a singleset of fields:
- index_together = ["pub_date", "deadline"]
constraints
A list of constraints that you want todefine on the model:
- from django.db import models
- class Customer(models.Model):
- age = models.IntegerField()
- class Meta:
- constraints = [
- models.CheckConstraint(check=models.Q(age__gte=18), name='age_gte_18'),
- ]
verbose_name
- verbose_name = "pizza"
If this isn't given, Django will use a munged version of the class name:CamelCase
becomes camel case
.
verbose_name_plural
- verbose_name_plural = "stories"
If this isn't given, Django will use verbose_name
+ "s"
.