如何编写这个Django查询?

2024-09-30 03:22:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我在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]
    ... 
}

我该怎么做


Tags: themodel排序顺序titlemodels文章order
2条回答

如果两个模型总是按同一列排序,那么您可以向每个模型的元数据添加默认排序

class ArticleSection(models.Model):
    class Meta:
        ordering = ['order']

class Article(models.Model):
    class Meta:
        ordering = ['order']

查询通常是“平面的”,因为它不包含层次结构。但是,您可以自己对对象进行后期处理。我们可以使用^{} 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等)中,插入顺序本身就不会得到尊重

相关问题 更多 >

    热门问题