强制与模型继承一起独特

时间:2013-03-01 15:01:50

标签: python django inheritance django-models

我试图解决下面的问题,经过一些搜索后,似乎在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 <bound method Command.inner_run of <django.contrib.staticfiles.management.commands.runserver.Command object at 0x10f85a0d0>>
Traceback (most recent call last):
  File "/Users/intelliadmin/VirtualEnvs/virtenv9/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 91, in inner_run
    self.validate(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.

1 个答案:

答案 0 :(得分:4)

可能的解决方案:

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()