Django模型在两种方式下都是唯一的 [英] Django model unique together both ways

查看:27
本文介绍了Django模型在两种方式下都是唯一的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

已经有许多关于此主题的问题,但不是我要搜索的内容.

Many questions already on this topic, but not what i'm searching for.

我有这个 Model :

class Options(TimeStampedModel)
    option_1 = models.CharField(max_length=64)
    option_2 = models.CharField(max_length=64)

    class Meta:
        unique_together = ('option_1', 'option_2')

现在,我对字段有唯一的约束.有没有一种方法也可以用另一种方式来定义它,这样无论什么是 option_1 和什么是 option_2

Now I have a unique constraint on the fields. Is there a way to also define this the other way around so that it doesn't matter what was option_1 and what was option_2

例如:

Options.create('spam', 'eggs') # Allowed
Options.create('spam', 'eggs') # Not allowed
Options.create('eggs', 'spam') # Is allowed but should not be

提前谢谢!

推荐答案

我认为ManyToMany 关系"rel ="nofollow noreferrer">通过表和"约束应该可以满足您的要求.

I think a ManyToMany relation with a custom through table and an unique_together constraint on that table should do what you want.

示例代码:

from django.db.models import Model, ForeignKey, ManyToManyField, CharField

class Option(Model):
    name = CharField()

class Thing(TimeStampedModel):
    options = ManyToManyField("Option", through="ThingOption")    

class ThingOption(Model):
    thing = ForeignKey(Thing)
    option = ForeignKey(Option)
    value = CharField()

    class Meta:
        unique_together = ('thing', 'option')

对于Django 2.2及更高版本,建议使用注释指出<将来可能不建议使用code> unique_together .请参阅帖子以了解它的用法.

For Django 2.2+ it is recommended to use UniqueConstraint. In the docs there is a note stating unique_together may be deprecated in the future. See this post for its usage.

这篇关于Django模型在两种方式下都是唯一的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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