Django模型两种方式都是独一无二的

时间:2018-04-13 12:27:11

标签: python django django-models unique-constraint

关于这个主题已有很多问题,但不是我正在寻找的问题。

我有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

无关紧要

例如:

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

提前致谢!

2 个答案:

答案 0 :(得分:3)

我认为与该表上的自定义ManyToMany表和through约束的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')

答案 1 :(得分:1)

您可以覆盖create方法,执行类似

的操作
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()