python - IntegrityError 没有在 None 上引发

标签 python django nonetype data-integrity

我有一个具有以下独特约束的模型:

class Record(Model):
    type = ForeignKey(Type, related_name='records')
    code = CharField(max_length=32)
    group = ForeignKey('self', null=True, blank=True, related_name='members')

    class Meta:
        unique_together = ('type', 'code', 'group')

我希望两条记录相同,如果它们都具有相同的类型和代码,并且都没有组。我预计会引发完整性错误,但这不会发生在以下测试用例中:

Record.objects.create(type=type_article_structure,
                      code='shoe',
                      group=None)
Record.objects.create(type=type_article_structure,
                      code='shoe',
                      group=None)

如果我为两者填充相同的组,唯一约束就会起作用:

group = Record.objects.create(type=type_article_structure,
                              code='group')
Record.objects.create(type=type_article_structure,
                      code='shoe',
                      group=group)
Record.objects.create(type=type_article_structure,
                      code='shoe',
                      group=group)

这导致:

django.db.utils.IntegrityError: UNIQUE constraint failed: md_masterdata_record.type_id, md_masterdata_record.code, md_masterdata_record.group_id

如何确保我在第一种情况下得到相同的错误?

附言。我的测试用例使用 SQLite,我的生产服务器使用 PostgreSQL。

最佳答案

Unique together 约束在数据库级别应用。许多数据库不会相互比较 null 值,因此让插入操作进入。

您可以通过覆盖模型中的 clean 方法来修复它。 clean 方法应用于提供自定义验证或在保存前修改字段值。另外,请注意,当您在对象上调用save时,不会调用 clean。它应该在调用 save` 方法之前调用。

from django.core.exceptions import ValidationError
class Record(Model):
    def clean(self):
        # check if exists
        if Record.objects.get(type=self.type,
                          code=self.code,
                          group=self.group):
              # raise an exception
              raise ValidationError("Exists")

关于python - IntegrityError 没有在 None 上引发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41769866/

相关文章:

python - 从脚本运行蜘蛛时获取 scrapycrawl 命令的功能

python-3.x - 检查 NoneType 的变量并中断 while 循环

python - 根据列表中的值修剪 Pandas DataFrame

python - 在 Mac 上安装 PyDrive

python - 使用aes在python中加密文件

javascript - Django 和使用模态窗口

python - 将 postgresql 与 sqlalchemy 连接起来

Django 查询以获取用户最喜欢的帖子?

python - 不断收到非类型错误

python - NoneType-Python 中的 Yield 错误