Django 查询集结果的顺序

Order of Django Queryset results

我无法理解为什么查询集会按其原先的顺序返回。我们为文章列出了作者,这些作者被存储在 ManyToMany table 中,名为:articlepage_authors

我们需要能够逐篇选择它们返回和显示的顺序。

例如,id 为 44918 的文章的作者为 13752(‘Lee Bodding’)和 13751(‘Mark Lee’)。

我在 shell 中调用了这些 returns :

Out[6]: <QuerySet [<User: Mark Lee (MarkLee@uss778.net)>, <User: Lee Bodding (LeeBodding@uss778.net)>]>

在 postgres 中调用:SELECT * FROM articlepage_authors;

显示用户 Lee Bodding id=13752 最先存储在 table.

id  | articlepage_id | user_id
-----+----------------+---------
   1 |          44508 |    7781
   2 |          44508 |    7775
   3 |          44514 |   17240
….
 465 |          44916 |   17171
 468 |          44918 |   13752
 469 |          44918 |   13751

无论我尝试什么删除作者,添加“Lee Bodding”,保存文章,然后添加“Mark Lee”,反之亦然——我仍然只能得到一个查询集,其中 returns “Mark Lee”在前。

我不知道还有什么调试方法。

一个解决方案是添加另一个定义作者顺序的字段,但我想先了解这里发生了什么。有些东西似乎已经在定义顺序,最好管理它。

您可以添加 an order_by to your queryset 以使记录按您希望的顺序显示。警告:对于查询优化,出于性能原因,您可能需要在该字段上创建索引,具体取决于数据库:

By default, results returned by a QuerySet are ordered by the ordering tuple given by the ordering option in the model’s Meta. You can override this on a per-QuerySet basis by using the order_by method. Example:

Entry.objects.filter(pub_date__year=2005).order_by('-pub_date', 'headline')

The result above will be ordered by pub_date descending, then by headline ascending. The negative sign in front of "-pub_date" indicates descending order. Ascending order is implied.

你将其与 an extra to order by the many-to-many ID 配对:

.extra(select={
    'creation_seq': 'articlepage_authors.id'
}).order_by("creation_seq")

如果您使用的是 django > 1.10,您可以直接使用该字段而无需 extra:

.order_by('articlepage_authors.id')