概述
我试图解决下面的问题,经过一些搜索后,似乎是在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
%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 – 与模型继承一起强制唯一全部内容,希望文章能够帮你解决python – 与模型继承一起强制唯一所遇到的程序开发问题。
如果您也喜欢它,动动您的小指点个赞吧