python django model联合主键

本文介绍了如何使用Django的Model元选项进行模型元数据配置,包括设置排序方式、表名和可读名称等。详细解释了unique_together选项的用法,通过实例展示了如何为模型设置联合唯一约束。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值