2017-01-20 39 views
2

我有一个具有以下独特的约束的模型:IntegrityError没有提出对无

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。

回答

4

唯一一起约束在数据库级别应用。许多数据库没有比较null的值,因此请插入操作。

您可以通过在模型中重写clean方法来修复它。应使用clean方法提供自定义验证或在保存前修改字段值。另外,请注意清洁is not invoked when you call保存on the object. It should be invoked before calling the保存方法。

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

感谢您的回答。不幸的是,我不明白这个例子。该代码不应该在方法中吗? – physicalattraction

+0

我忘了写方法签名:) –

+0

那我还是不明白。当然,字符串'shoe'就是一个例子,不应该被硬编码。我是否可以通过此方法访问'self.code'等? – physicalattraction

0

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