django中的model 的unique_together(聯合唯一)


unique_together解釋

nique_together

這個元數據是非常重要的一個!它等同於數據庫的聯合約束!

舉個例子,假設有一張用戶表,保存有用戶的姓名、出生日期、性別和籍貫等等信息。要求是所有的用戶唯一不重復,可現在有好幾個叫“張偉”的,如何區別它們呢?(不要和我說主鍵唯一,這里討論的不是這個問題)

我們可以設置不能有兩個用戶在同一個地方同一時刻出生並且都叫“張偉”,使用這種聯合約束,保證數據庫能不能重復添加用戶(也不要和我談小概率問題)。在Django的模型中,如何實現這種約束呢?

使用unique_together,也就是聯合唯一!

比如:

unique_together = (('name', 'birth_day', 'address'),)

這樣,哪怕有兩個在同一天出生的張偉,但他們的籍貫不同,也就是兩個不同的用戶。一旦三者都相同,則會被Django拒絕創建。這一元數據經常被用在admin后台,並且強制應用於數據庫層面。

unique_together接收一個二維的元組((xx,xx,xx,...),(),(),()...),每一個元素都是一個元組,表示一組聯合唯一約束,可以同時設置多組約束。為了方便,對於只有一組約束的情況下,可以簡單地使用一維元素,例如:

unique_together = ('name', 'birth_day', 'address')

聯合唯一無法作用於普通的多對多字段。

例如我的表關系是:

from django.db import models

# Create your models here.
from django.contrib.auth.models import  AbstractUser

time_choices = (
    (1, '8:00'),
    (2, '9:00'),
    (3, '10:00'),
    (4, '11:00'),
    (5, '12:00'),
    (6, '13:00'),
    (7, '14:00'),
    (8, '15:00'),
    (9, '16:00'),
    (10, '17:00'),
    (11, '18:00'),
    (12, '19:00'),
    (13, '20:00'),
)

class UserInfo(AbstractUser):
    pass




class Room(models.Model):
    """
    會議室表
    """
    caption = models.CharField(max_length=32)
    num = models.IntegerField()
    def __str__(self):
        return self.caption


class Book(models.Model):
    """
    會議室預定信息
    """
    user = models.ForeignKey('UserInfo',on_delete=models.CASCADE)
    room = models.ForeignKey('Room',on_delete=models.CASCADE)
    date = models.DateField()
    time_id = models.IntegerField(choices=time_choices)

    class Meta:
        unique_together = (
            ('room','date','time_id'),  # 聯合唯一
        )

    def __str__(self):
        return str(self.user)+"預定了"+str(self.room)

 

 

參考:https://blog.csdn.net/qqizz/article/details/80020762


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM