2017-11-01 1 views
0

내가 아래 모델을 가지고 내가하려고 할 때 내가 many2many 필드액세스 many2many 필드 값 깨끗한 방법으로 데이터베이스에 저장하기 전에

RULE_SET_CHOICES = (
    ('G', 'GLOBAL'), 
    ('C', 'LOCAL') 
) 

class Books(models.Model): 
    type = models.CharField(max_length=2, choices=RULE_SET_CHOICES, null=False, default='C') 
    author = models.ManyToManyField(Author, related_name="books", blank=True, null=True) 

    def clean(self): 
     if self.type = 'G': 
      // Check if type is Global and if we tried to associate/add authors then raise a validation error 
      if self.author : 
       raise ValidationError("When type is global, you should not associate authors") 

의 값에 따라 청소 방법의 유효성 검사 오류를 높이기 위해 노력하지만,하고 장고 액세스 self.author에 나는

*** ValueError: "<Books: Hello World- G>" needs to have a value for field "author " before this many-to-many relationship can be used 

그래서 데이터베이스에 저장하기 전에 많은-2-많은 관계 필드 값에 액세스 할 수있는 방법이 오류 아래에 직면하고있다? 위와 같이 해당 값을 기준으로 유효성 검사 오류를 발생시켜야하므로

답변

0

유효성 검사를 위해 모델 양식을 사용하는 경우 self.cleaned_data의 양식 필드에 액세스 할 수 있습니다.

모델의 clean 메서드에서 값을 확인하는 방법을 모르겠습니다. many-to-many 필드에 접근하기 전에 self.pk을 체크 할 것입니다.

self.author는 관련 관리자입니다
def clean(self): 
    if self.pk and self.type = 'G': 
     ... 

주, 그래서 if self.author은 항상 true가됩니다. 아마도 당신은 self.author.exists()을 원할 것입니다. 저자가 한 명 이상일 수 있으므로 authors 필드의 이름을 지정하는 것이 좋습니다.

관련 문제