django:相关字段的查找无效

时间:2011-06-19 05:08:09

标签: django django-models

我有以下型号

class SchoolClass(models.Model):
    id = models.AutoField(primary_key = True)
    class_name = models.TextField()
    level = models.IntegerField()
    taught_by = models.ManyToManyField(User,related_name="teacher_teaching",through='TeachSubject')
    attended_by = models.ManyToManyField(User,related_name='student_attending',through='StudentClassHistory')

    def __unicode__(self):
        return self.class_name
    class Meta:
        db_table = 'classes'

class StudentClassHistory(models.Model):
    student = models.ForeignKey(User)
    year = models.IntegerField(default=datetime.date.today().year)
    semester = models.IntegerField()
    attended_class  = models.ForeignKey(SchoolClass) 

    class Meta:
        db_table = 'student_class_history'

当我尝试运行以下查询时

User.objects.filter(student_attending__studentclasshistory__year=2011)

我收到错误Related Field has invalid lookup: year。这很奇怪,因为我省略了年份,可用字段为Cannot resolve keyword '' into field. Choices are: attended_class, id, semester, student, year

这是怎么回事?

另外,在我的模型属性中使用through时,我可以删除related_name吗?

1 个答案:

答案 0 :(得分:23)

问题是year is a field lookup,所以Django认为你试图从不是约会的东西中提取年份。你应该写:

User.objects.filter(student_attending__studentclasshistory__year__exact=2011)

(另外,你应该让defaultyear一个可调用的,即:

year = models.IntegerField(default=lambda: datetime.date.today().year)