2014-03-06 45 views
0

訪問ForeignKey的_id場得到了一個意想不到的關鍵字參數我有一個模型,它看起來像這樣:Django的:而在經理

class Mentorship (models.Model): 
    mentor = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='mentor_user_id') 
    mentee = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='mentee_user_id') 

    objects = MentorshipManager() 

    def clean(self): 
     print(self.mentor_id) # is set and printed to stdout 
     print(self.mentee_id) # is set and printed to stdout 

     if Mentorship.objects.is_mentor(self.mentor_id, self.mentee_id): 
      raise ValidationError(_('This user is already a mentor.')) 

經理有一個函數來檢查,如果有人已經是另一個用戶的導師,這就是所謂的同時clean()荷蘭國際集團的實例:

def is_mentor_for_goal(self, mentor_id, mentee_id, personal_goal_id): 
    if self.exists(mentor_id=mentor_id, mentee_id=mentee_id): 
     return True 
    else: 
     return False 

在訪問mentor_idmentee_id屬性的存在但我總是得到一個異常:

Django Version:  1.6.1 
Exception Type:  TypeError 
Exception Value: exists() got an unexpected keyword argument 'mentor_id' 

是否有原因導致我無法訪問管理器中的_id字段?我只是不明白爲什麼該字段可以在(未保存的)實例中訪問,但不能在管理器中訪問。

+0

試試這個:'mentor__id = mentor_id'。 –

回答

0

有幾件事情mentor__id只會queryset的方法,而不是之類的東西print工作。您還應該使用pk代替id,這裏是它如何工作的:

class Mentorship(models.Model): 
    mentor = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='mentor_user_id') 
    mentee = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='mentee_user_id') 

    objects = MentorshipManager() 

    def clean(self): 
     print(self.mentor.pk) # is set and printed to stdout 
     print(self.mentee.pk) # is set and printed to stdout 

     if Mentorship.objects.filter(mentor=self.mentor).exists(): 
      raise ValidationError(_('This user is already a mentor.')) 

def is_mentor_for_goal(self, mentor_id, mentee_id, personal_goal_id): 
    return self.exists(mentor__pk=mentor_id, mentee__pk=mentee_id) 
1

哦... ...的人...這應該叫

if self.filter(mentor_id=mentor_id, mentee_id=mentee_id).exists() 

感謝您的意見