django:在Manager中访问ForeignKey _id-Field时得到一个意外的关键字参数

时间:2014-03-06 12:05:55

标签: django django-models django-queryset django-managers

我的模型看起来像这样:

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字段吗?我只是不明白为什么该字段可以在(未保存的)实例中访问,但不能在管理器中访问。

2 个答案:

答案 0 :(得分:1)

哦......男人......应该叫做

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

感谢您的评论

答案 1 :(得分:0)

一些事情mentor__id仅适用于查询集方法,而不适用于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)