[英]How can I write this django query?
我在 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(..)
函数 [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 词典使用插入顺序(自python-3.7 起),但如果您使用不同的格式,如 JSON,则其本身不会尊重不同环境(JavaScript 等)中的插入顺序。
如果 btoth 模型总是按同一列排序,那么您可以为每个模型的 Meta 添加默认排序
class ArticleSection(models.Model):
class Meta:
ordering = ['order']
class Article(models.Model):
class Meta:
ordering = ['order']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.