6

我试图解决下面的问题,经过一番搜索,它似乎是 Django 中的一个开放错误。我通过向模型子类添加一个类方法解决了这个问题,虽然这个解决方案有效,但它仍然需要使用这个子类对任何 (Model)Form 进行另一个自定义检查。我将其发布给其他人,以便比我更快地找到解决方案,也欢迎其他解决方案。

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.
4

1 回答 1

5

一个可能的解决方案:

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()
于 2013-03-01T15:01:50.410 回答