python - 我该如何编写这个 django 查询?

标签 python django python-3.x django-rest-framework

我在 django 中有以下模型,它们代表文章及其部分。文章有一个顺序/索引,表示文章在某个部分中的相应顺序,并且部分也有一个顺序,以便它们也可以与其他部分一起排序。

class ArticleSection(models.Model):
    title = CharField(max_length=50)
    order = PositiveIntegerField()  # the sections order with other sections

    def __str__(self):
        return self.title


class Article(models.Model):
    section = models.ForeignKey(
        ArticleSection, on_delete=models.CASCADE)
    content = CharField(max_length=100)
    order = PositiveIntegerField()  # the articles order in the section its in

我想要做的是获取文章列表,按文章顺序排序,按部分分组,最后按部分顺序排序。所以我基本上结果应该是这样的:

{
    section4: [article1, article2, article20],
    section8: [article1, article2, article3]
    ... 
}

我该怎么做?

最佳答案

查询通常是“扁平的”,因为它不包含层次结构。不过,您可以自己对对象进行后处理。我们可以通过 groupby(..) function [python-doc] 来做到这一点:

from itertools import groupby
from operator import attrgetter

qs = Article.objects.select_related(
    'section'
).order_by('section__order', 'section_id', 'order')

result = {
    section: list(articles)
    for section, articles in groupby(qs, attrgetter('section'))
}

请注意,虽然 Python 字典使用插入顺序(自 起),但如果您使用不同的格式(例如 JSON),则本身不会尊重不同环境(JavaScript 等)中的插入顺序。

关于python - 我该如何编写这个 django 查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59547462/

相关文章:

python - 通过 FEniCS 求解热方程

django - 如何在 Django ORM 中更改 PostgreSQL 的默认空排序行为

django - 如何改变南迁顺序

python - 如何装饰 Python 3 中的部分应用函数?

python-3.x - python 3的Virtualenvwrapper替代品

python-3.x - 由于 'c' 参数无效,无法使用 plt.scatter 进行绘图

Python 元编程 : generate a function signature with type annotation

python - 将列表与字典进行比较 - 如果值与列表匹配则返回键

python - 使用带有自定义类的图形生成器作为节点

python - django 分页不适用于 django 过滤器