Meta
options¶
Give your model metadata by using an inner class Meta
, like so:
from django.db import models
class Ox(models.Model):
horn_length = models.IntegerField()
class Meta:
ordering = ["horn_length"]
verbose_name_plural = "oxen"
Model metadata is “anything that’s not a field”, such as ordering options(ordering
), database table name (db_table
), orhuman-readable singular and plural names (verbose_name
andverbose_name_plural
). None are required, and adding classMeta
to a model is completely optional.
Meta
options can be found in the
modeloption reference.
unique_together
¶
-
Sets of field names that, taken together, must be unique:
unique_together = (("driver", "restaurant"),)
This is a tuple of tuples 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 theCREATE TABLE
statement).For convenience, unique_together can be a single tuple when dealing with a singleset 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 explicitthrough
model.The
ValidationError
raised during model validation when the constraintis violated has theunique_together
error code.
Options.
unique_together
¶
例如:
class user(Model):
id=AutoField(primary_key=True)
name = CharField(max_length=30)
age =IntegerField()
class role(Model):
id=AutoField(primary_key=True)
name=CharField(max_length=10)
这是两个model有一个roleUser的model来描述use与role的关系,需要user的id与role的id做外键,也做联合主键,如下:
class roleUser(Model): userId=ForeignKey(user) roleId=ForeignKey(role) class Meta: unique_together=("userId","roleId")其中:
class Meta: unique_together=("userId","roleId")
就是建立联合主键。