Django Unique Together(带外键) [英] Django Unique Together (with foreign keys)

查看:25
本文介绍了Django Unique Together(带外键)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种情况,我想使用 unique_together 的 Meta 选项来强制执行某个规则,这是中间模型:

I have a situation where I want to use the Meta options of unique_together to enforce a certain rule, here's the intermediary model:

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"))

这里是用户配置文件:

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

谢谢.

推荐答案

你不能.

unique_together 子句直接转换为 SQL 唯一索引.并且只能在单个表的列上设置,不能在多个表的组合上设置.

The unique_together clause is directly translated to the SQL unique index. And you can only set those on columns of a single table, not a combination of several tables.

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

You can add validation for it yourself though, simply overwrite the validate_unique method and add this validation to it.

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

这篇关于Django Unique Together(带外键)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆