2017-01-20 7 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 

첫 번째 경우에도 동일한 오류가 발생합니다. 어떻게해야합니까?

추신. 내 테스트 케이스는 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

나는 아직도 그때를 이해하지 못한다. 물론 문자열 '신발'이 예제이며 하드 코드되지 않아야합니다. 이 메소드에서'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()