I have the following 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.In开发者_C百科tegerField()
attended_class = models.ForeignKey(SchoolClass)
class Meta:
db_table = 'student_class_history'
When i try to run the following query
User.objects.filter(student_attending__studentclasshistory__year=2011)
i got the error Related Field has invalid lookup: year
. That's strange, because i omitted year and the available fields are Cannot resolve keyword '' into field. Choices are: attended_class, id, semester, student, year
How is this so?
Also, with through
in my model attribute, can I just remove related_name
?
The problem is that year
is a field lookup, so Django thinks you're trying to extract the year from something which isn't a date. You should write:
User.objects.filter(student_attending__studentclasshistory__year__exact=2011)
(Also, you ought to make the default
for year
a callable, i.e.:
year = models.IntegerField(default=lambda: datetime.date.today().year)
)
精彩评论