2009-03-10 2 views
1

을 저장하기 전에 ManyToManyField에 객체를 추가 그렇지 않으면 너무.장고 모델 조건부 다음, 그 목적은 확실히 작품 않습니다

class JobRecord(models.Model): 
    """JobRecord model""" 

    project    = models.ForeignKey(Project) 
    date    = models.DateField() 
    supervisor   = models.ForeignKey(User, related_name='supervisor_set') 

    operators   = models.ManyToManyField(User, related_name='operators_set', help_text='Include the supervisor here also.') 

    vehicles   = models.ManyToManyField(Vehicle, blank=True, null=True) 

    def __unicode__(self): 
     return u"%s - %s" % (self.project.name, self.date.strftime('%b %d')) 

    # --- over ride methods ---- # 

    def save(self, **kwargs): 
     # this must be done to get a pk 
     super(JobRecord, self).save(**kwargs) 

     # which makes this comparison possible 
     if self.supervisor not in self.operators.__dict__: 
      self.operators.add(self.supervisor) 

     # it seems to get this far ok, but alas, the second save attempt 
     # does not seem to work! 
     print self.operators.values() 
     super(JobRecord, self).save(**kwargs) 

'전문가'입니다.

+0

임의 코드 검토 주석. if() 뒤에 save() 메서드를 이동하고 dedent를 호출하면 한 번만 호출하면됩니다. – monkut

답변

2

당신은 관리자가 운영자에 있는지 확인하기 위해이 같은 작업을 수행 할 수 있습니다

if self.operators.filter(id=self.supervisor.id).count() == 0: 

그리고 당신은 많은 분야에 많은 수정 한 후 두 번째 시간을 절약 할 필요가 없습니다. (다 대다 관계는 자체 테이블에 저장됩니다.)

+0

절반 방법 ... 조건부 작품, 아직 add() 메서드는 꽤 그것을 균열하지 않습니다? –

1

좋아, 다음을 수정했습니다. 실제로 조건 중 하나가 트릭을 수행하는 것으로 보입니다. 이제 문제는 add() 메서드가 나를 위해 작동하지 않는다는 것입니다.

#... 

def save(self, **kwargs): 
    super(JobRecord, self).save(**kwargs) 

    if self.operators.filter(id=self.supervisor.id).count() == 0: 
    #if self.supervisor not in self.operators.values(): 

     # either conditional will get to this point 
     self.operators.add(self.supervisor) # <-- this line doesn't save proper? 
+0

정말로 추가하지 않습니까? 예외가 있습니까? self.operators.all()을 인쇄 해보십시오. –

+0

다 대다 API 사용법을 검토하고 싶을 수도 있습니다 : http://www.djangoproject.com/documentation/models/many_to_many/ –

0

나는 동일한 문제가 있습니다. django 폼을 사용하고 있다면, 폼이 저장된 후에 체크를 한 다음, 거기에 많은 것을 추가하십시오. 그게 그걸 해결할 수있는 유일한 방법 이었어.