我在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]
...
}
我该怎么做
如果两个模型总是按同一列排序,那么您可以向每个模型的元数据添加默认排序
查询通常是“平面的”,因为它不包含层次结构。但是,您可以自己对对象进行后期处理。我们可以使用^{} function [python-doc]:
请注意,尽管Python字典使用插入顺序(因为python-3.7),但是如果您使用不同的格式(如JSON),那么在不同的环境(JavaScript等)中,插入顺序本身就不会得到尊重
相关问题 更多 >
编程相关推荐