【发布时间】:2017-06-05 19:25:24
【问题描述】:
我有一个具有以下独特约束的模型:
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。
【问题讨论】:
标签: python django nonetype data-integrity