您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

5b51 2022/1/14 8:20:46 python 字数 3152 阅读 454 来源 www.jb51.cc/python

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

概述

我试图解决下面的问题,经过一些搜索后,似乎是在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 – 与模型继承一起强制唯一所遇到的程序开发问题。


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶