您的位置:首页 > 编程语言 > Python开发

python django model联合主键

2018-03-29 10:19 411 查看
https://docs.djangoproject.com/en/2.0/topics/db/models/#meta-options

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
and
verbose_name_plural
). None are required, and adding
classMeta
to a model is completely optional.A complete list of all possible
Meta
options can be found in the modeloption reference.

https://docs.djangoproject.com/en/2.0/ref/models/options/#unique-together

unique_together

Options.
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 the
CREATE 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 a
ManyToManyField
, try using a signal oran explicit
through
model.The
ValidationError
raised during model validation when the constraintis violated has the
unique_together
error code.

今天,在家试试django的model的设置,如何设置的联合主键,我经过查资料和实践,把结果记录如下:      例如: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")
就是建立联合主键。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: