2017-01-20 3 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') 

私は彼らの両方が同じタイプとコードを持っている、との両方が、何のグループを持っていない場合、2つのレコードが同じになりたいです。私は、整合性エラーが発生することが予想されるが、これは、次のテストケースでは発生しません:

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) 

この結果をin:

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メソッドをオーバーライドすることで修正できます。メソッドを使用して、カスタム検証を提供するか、保存する前にフィールド値を変更する必要があります。また、清潔なis not invoked when you call保存on the object. It should be invoked before calling the 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") 
+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() 
関連する問題