gpt4 book ai didi

django:相关字段查找无效

转载 作者:行者123 更新时间:2023-12-04 09:21:14 24 4
gpt4 key购买 nike

我有以下型号

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 ?

最佳答案

问题是 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)

)

关于django:相关字段查找无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6400683/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com