IntegrityError 未在 None 上引发

IntegrityError not raised on None

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

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

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

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

1)

try:
    //somthing
except IntegrityError as e:
    print("integrity")
except Exception as e:
    print(e)`

2)检查

record=Record(type=type_article_structure,
                  code='shoe',
                  group=None)
record.save()

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

您可以通过覆盖模型中的 clean 方法来修复它。 clean 方法应该用于提供自定义验证或在保存前修改字段值。另外,请注意 cleanis not invoked when you callsaveon the object. It should be invoked before calling thesave` 方法。

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