python – 与模型继承一起强制唯一

我试图解决下面的问题,经过一些搜索后,似乎是在Django中开放的bug.我通过向模型子项添加方法解决该问题,虽然此解决方案有效,但仍需要使用此子类对任何(模型)表单进行另一次自定义检查.我发布这个比其他人更快找到解决方案,其他解决方案也是受欢迎的.

class Foo(models.Model):
    attr1 = models.IntegerField()
    attr2 = models.IntegerField()

    class Meta:
        unique_together = (
            ('attr1','attr2'),)


class Bar(Foo):
    attr3 = models.IntegerField()

    class Meta:
        unique_together = (
            ('attr1','attr3'),)

提出:

Unhandled exception in thread started by display_num_errors=True)
  File "/Users/intelliadmin/VirtualEnvs/virtenv9/lib/python2.7/site-packages/django/core/management/base.py",line 270,in validate
    raise CommandError("One or more models did not validate:\n%s" % error_text)
django.core.management.base.CommandError: One or more models did not validate:
app.Bar: "unique_together" refers to attr1. This is not in the same model as the unique_together statement.
最佳答案
可能的解决方案:

class Bar:
    # fields...

    @classmethod
    def _validate_unique(cls,self):
        try:
            obj = cls._default_manager.get(attr1=self.attr1,attr3=self.attr3)
            if not obj == self:
                raise IntegrityError('Duplicate')
        except cls.DoesNotExist:
            pass

    def clean(self):
        self._validate_unique(self)
        super(Bar,self).clean()

相关文章

我最近重新拾起了计算机视觉,借助Python的opencv还有face_r...
说到Pooling,相信学习过CNN的朋友们都不会感到陌生。Poolin...
记得大一学Python的时候,有一个题目是判断一个数是否是复数...
文章目录 3 直方图Histogramplot1. 基本直方图的绘制 Basic ...
文章目录 5 小提琴图Violinplot1. 基础小提琴图绘制 Basic v...
文章目录 4 核密度图Densityplot1. 基础核密度图绘制 Basic ...