python django model联合主键

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.

A complete list of all possible Meta options can be found in the modeloption reference.



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 TABLEstatement).

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 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")
就是建立联合主键。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值