Django-filter 和 Django-tables2 使用外部属性

Django-filter and Django-tables2 Using a foreign attribute

我已经通读了之前的问题,并尝试阅读文档,但我没有真正的运气。

我正在使用 Django-tables2 来显示学生的数据。

table(当前排名)中的一列使用学生模型中模型管理器的访问器填充,如下所示:

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"] 

table 可以正确填充和显示,但排序依据会产生错误。我可以按如下方式调整列:

current_standing = tables.Column(accessor='get_current_standing', order_by='academicstanding.standing')

但是因为关系是 1:N 我得到了多个结果,其中(如学生模型中的经理所示),我只想要学生在特定入学年份的学术地位。此方法也不会根据排名对条目进行分组。

最后,这种使用模型管理器作为访问器填充 table 的方法是否正确?我缺少什么来启用正确的预期功能?

好的,这很有趣。如果你给我一个存储库会更快,但是你提供了很多信息,所以我能够毫无困难地制作我自己的。 :D 在撰写本文时已经 here, (commit e7f70e

为了整洁起见,我在 QuerySet 中做了所有重要的事情,所以请看一下 students/managers.py

在这里,您会看到我在上面的评论中难以理解的注释。我已将其翻译成以下更独立的内容:

Student.objects.annotate(current_standing=models.Subquery(
    AcademicStanding.objects \
        .filter(student=models.OuterRef('id')) \
        .filter(year__year=2018) \
        .values('standing'),
    )
)

适用于以下型号:

class Student(models.Model):
    name = models.CharField(max_length=20, ...)

    ...


class AcademicStanding(models.Model):
    student = models.ForeignKey(
        'students.Student',
        related_name='academic_standings',
        on_delete=models.CASCADE,
    )
    standing = models.PositiveIntegerField()
    year = models.DateField()

    ...

查询利用 models.Subquery 来做一个子查询,使用 OuterRef 来引用当前行的 id,这意味着每个 Student 都会得到他们的自己 AcademicStanding 与他们相关联,而不是集合中的第一个 AcademicStanding,没有那个过滤器。

我们的 table 定义如下,所有 "just works" 作为我们感兴趣的值现在都在查询集上。所有性能也都保持不变,因为这实际上是在数据库内完成的计算,而不是在 Python 中使用多个查询。

class StudentTable(tables.Table):

    class Meta:
        model = Student
        fields = ['name', 'current_standing']

我在途中学到的一件很酷的事情是关于 RequestConfig。这是 django-tables2 中的内容,它接受当前请求,并自动执行 table 所需的内容以匹配 GET 参数等。您可以在实际操作中看到这一点 here。这对我来说是全新的。


对于您的问题 2 - 我怀疑您会发现使用我上面详述的注释更容易推理和实施,但如果不是,请 post 另一个问题。

(这样我可以得到更多的答案分)。 :P