一尘不染

Django Unique Together(带外键)

python

我遇到一种情况,我想使用Meta选项unique_together来强制执行某条规则,这是中介模型:

class UserProfileExtension(models.Model):
    extension = models.ForeignKey(Extension, unique=False)
    userprofile = models.ForeignKey(UserProfile, unique=False)
    user = models.ForeignKey(User, unique=False)

    class Meta:
        unique_together = (("userprofile", "extension"),
                           ("user", "extension"),
                           # How can I enforce UserProfile's Client 
                           # and Extension to be unique? This obviously
                           # doesn't work, but is this idea possible without
                           # creating another FK in my intermediary model 
                           ("userprofile__client", "extension"))

这是UserProfile:

class UserProfile(models.Model):
    user = models.ForeignKey(User, unique=True)
    client = models.ForeignKey(Client)

谢谢。


阅读 170

收藏
2020-12-20

共1个答案

一尘不染

你不能

unique_together子句直接转换为SQL唯一索引。而且,您只能在单个表的列上设置这些值,而不能在多个表的组合上设置。

不过,您可以自己为其添加验证,只需覆盖该validate_unique方法并将此验证添加到其中即可。

文件:http
:
//docs.djangoproject.com/en/dev/ref/models/instances/#django.db.models.Model.validate_unique

2020-12-20