2011-06-19 223 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