Django独一无二(带外键) [英] Django Unique Together (with foreign keys)

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

问题描述

我有一种情况,我想使用 unique_together 的元选项执行某个规则,这里是中介模型:

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

和这里的UserProfile:

and here's UserProfile:

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独一无二(带外键)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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