【发布时间】:2018-01-31 15:18:40
【问题描述】:
我已经阅读了以前的问题,并尝试在文档中阅读,但我对此并没有真正的运气。
我正在使用 Django-tables2 来显示学生的数据。
表中的一列(当前排名)使用学生模型中的模型管理器的访问器填充,如下所示:
models.py
class Student(models.Model):
#a bunch of fields
def get_current_standing(self):
current_standing = AcademicStanding.objects.get(year=self.enrol_term, student=self).standing
return current_standing
tables.py
class StudentTable(tables.Table):
current_standing = tables.Column(accessor='get_current_standing')
class Meta:
model = Student
fields = ["last_name", "first_name", "campus_id", "current_standing"]
表格可以正确填充和显示,但排序依据会产生错误。我可以按如下方式调整 Column:
current_standing = tables.Column(accessor='get_current_standing', order_by='academicstanding.standing')
但是因为关系是 1:N,所以我得到了多个结果,其中(如学生模型中的经理所示),我只想要该特定入学年份的学生的学术地位。此方法也不会根据排名对条目进行分组。
最后,这种使用模型管理器作为访问器填充表的方法是否正确?为了启用正确的预期功能,我缺少什么?
【问题讨论】:
-
如果您有多个问题,您应该发布多个问题。 :( 对于问题 1,您应该能够使用
.annotate()而不是访问器,这将解决您的排序问题,并摆脱固有的 N+1 选择问题......但我不太确定如何做那种注释来发布答案。 -
@AdamBarnes 谢谢你。我认为将它们组合在一起会更好,并且可以更全面地了解我想要实现的目标。
-
嗯...可能吗?也许我太仓促了,因为看起来这甚至可能不是两个问题,因为注释可以解决这两种情况......我不认为您可以将您的问题和一些示例数据放在存储库中?那么,我将尝试实施我所描述的内容。
-
@AdamBarnes 如果我理解正确,我只需将 .annotate(currentstanding='academicstanding__standing') 添加到过滤器的查询集中。但是我现在得到“str”对象没有属性“resolve_expression”-我在这里做错了什么?
-
我真的不确定;这是我需要让我的手指粘在代码中才能理解的事情之一。现在让我拼凑一个玩具项目,看看我能做什么。
标签: python django django-tables2