2011-06-19 172 views
7

我有以下型号Django的:相关领域具有无效查找

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

回答

23

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

User.objects.filter(student_attending__studentclasshistory__year__exact=2011) 

(另外,你应该让default用于year可调用,即:

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

+0

bahh,解释它。谢谢。另一个qns:如果我输入过滤器(student_attending ____ schoolclasshistory = ...),我会在我的查询中得到重复的条目,即与schoolclasshistory中的条目数成正比。然而过滤器(schoolclasshistory = ..)是好的。为什么这样呢? – goh