Django模型的双向唯一约束

2024-03-28 23:00:55 发布

您现在位置:Python中文网/ 问答频道 /正文

关于这个话题已经有很多问题了,但不是我要找的。在

我有这个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还是{}

例如:

^{pr2}$

提前谢谢!在


Tags: 方法modelmodels方式lengthmaxmetaclass
2条回答

我认为带有自定义through表的ManyToMany关系和该表上的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。在文档中有一个note声明unique_together将来可能会被弃用。请参阅this帖子了解其用法。在

您可以重写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()

相关问题 更多 >