Django meta unique_together在递归模型上

时间:2016-08-04 13:04:45

标签: django django-models django-admin

我宣布了一个递归模型,如下所示。如何修改或添加另一个unique_together Meta,以便recursiveA字段不能包含已存在的名称和标记组合?

如果name =' a' AND marker =' b'然后recursiveA.name!=' a' AND recursiveA.marker!=' b'

class A(models.Model):
    name = models.CharField(max_length=32)
    marker = models.CharField(max_length=32)
    recursiveA = models.ManyToManyField('self', blank=True)

    class Meta:
        unique_together = ('name', 'marker')

1 个答案:

答案 0 :(得分:0)

您可以覆盖save方法:

class A(models.Model):
    name = models.CharField(max_length=32)
    marker = models.CharField(max_length=32)
    recursiveA = models.ManyToManyField('self', blank=True)

    class Meta:
        unique_together = ('name', 'marker')

    def save(self, *args, **kwargs):
        is_new = self.pk is not None
        if is_new:
            assert self.name != self.recursiveA.name and self.marker ! = self.recursiveA.marker
        return super().saver(*args, **kwargs)