2011-06-19 5 views
7

私はエラーRelated Field has invalid lookup: yearを持って次のクエリジャンゴ:関連フィールドが無効引き

User.objects.filter(student_attending__studentclasshistory__year=2011) 

を実行しようとすると、私は次のモデルに

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' 

を持っています。それは奇妙です。なぜなら私は年を省略し、利用可能なフィールドは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) 

(また、あなたがyearためdefault呼び出し可能を作るべき、すなわち:

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

+0

それを説明bahhを、。ありがとう。別のqns:私はフィルタを入力した場合(student_attending__schoolclasshistory = ...)私は私の質問で、つまりschoolclasshistoryのエントリの数に比例して繰り返される用語を取得します。しかし、フィルター(schoolclasshistory = ..)は良いです。なぜこれはそうですか? – goh

関連する問題