phy*_*ion 3 python django data-integrity nonetype
我有一个具有以下独特约束的模型:
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')
Run Code Online (Sandbox Code Playgroud)
我希望两条记录相同,如果它们都具有相同的类型和代码,并且都没有组。我预计会引发完整性错误,但在以下测试用例中不会发生这种情况:
Record.objects.create(type=type_article_structure,
code='shoe',
group=None)
Record.objects.create(type=type_article_structure,
code='shoe',
group=None)
Run Code Online (Sandbox Code Playgroud)
如果我为两者填充同一组,则唯一约束起作用:
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)
Run Code Online (Sandbox Code Playgroud)
这导致:
django.db.utils.IntegrityError: UNIQUE constraint failed: md_masterdata_record.type_id, md_masterdata_record.code, md_masterdata_record.group_id
Run Code Online (Sandbox Code Playgroud)
我如何确保在第一种情况下得到相同的错误?
附言。我的测试用例使用 SQLite,我的生产服务器使用 PostgreSQL。
唯一的共同约束应用于数据库级别。许多数据库不会null相互比较值,因此让插入操作进入。
您可以通过覆盖clean模型中的方法来修复它。clean方法应用于提供自定义验证或在保存之前修改字段值。另外,请注意 clean is not invoked when you callsave on 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")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1321 次 |
| 最近记录: |