Django 模型在两种情况下都是独一无二的

Django model unique together both ways

关于这个主题已经有很多问题,但不是我要搜索的。

我有这个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_1option_2

就无关紧要了

例如:

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

提前致谢!

你可以覆盖创建方法,做一些类似的事情

from django.db import models

class MyModelManager(models.Manager):
    def create(self, *obj_data):
        # Do some extra stuff here on the submitted data before saving...       
        # Ex- If obj_data[0]=="eggs" and obj_data[1]=="spam" is True don't allow it for your blah reason      
        # Call the super method which does the actual creation
        return super().create(*obj_data) # Python 3 syntax!!

class MyModel(models.model):
    option_1 = models.CharField(max_length=64)
    option_2 = models.CharField(max_length=64)

    objects = MyModelManager()

我认为对 table 的 ManyToMany relation with a custom through table and an unique_together 约束应该可以满足您的要求。

示例代码:

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+,建议使用UniqueConstraint. In the docs there is a note stating unique_together may be deprecated in the future. See this post。