加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-16 21:53:17 所属栏目:Python 来源:网络整理
导读:我试图解决下面的问题,经过一些搜索后,似乎是在Django中开放的bug.我通过向模型子项添加类方法来解决该问题,虽然此解决方案有效,但仍需要使用此子类对任何(模型)表单进行另一次自定义检查.我发布这个比其他人更快找到解决方案,其他解决方案也是受欢迎的. cla

我试图解决下面的问题,经过一些搜索后,似乎是在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 
最佳答案
可能的解决方案:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读