有没有一种方法可以使查询尊重输入参数的顺序? [英] Is there a way to make a query respect the order of the inputted parameters?

查看:93
本文介绍了有没有一种方法可以使查询尊重输入参数的顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(请让我知道这是否完全荒唐,这可能是为什么我没有发现任何东西的原因。)

这个故事有两个模型,分别是 Ranking Artist Ranking 通常与 Artist (object_id,content_type ...整个shebang)有关。

This story has two models Ranking and Artist, Ranking is generically related to Artist (object_id, content_type... the whole shebang).

我有一个列表由 Ranking.objects.values_list()返回的对象按特定字段排序(在本例中为得分)。因此很明显,如果我想显示已排名的艺术家的列表,我希望他们以相同的顺序。我尝试了不同的方法,例如 .filter(pk__in = list) .in_bulk(list)等。尝试将 .values_list()的结果也强制为一个元组。

I have a list of objects returned by Ranking.objects.values_list() ordered by a certain field (in my case score). So obviously, if I want to display a list of artists that were ranked, I'd want them in the same order. I've tried different methods, such as .filter(pk__in=list), .in_bulk(list), etc. Tried coercing the result of .values_list() into a tuple too.

它们都接受了我的列表:

They all take my list:

>>> objects = Ranking.objects.filter(<stuff>).order_by('score')
>>> objects_list = objects.values_list('object_id', flat=True)
>>> objects_list
[8, 1, 2, 15, 14, 3, 13, 31, 16, 5, 4, 7, 32, 9, 37]

并像这样返回它:

>>> Artist.objects.filter(id__in=objects_list).values_list('id', flat=True)
[7, 32, 3, 8, 4, 2, 31, 9, 37, 13, 16, 1, 5, 15, 14]

(出于第二种情况,我只是给出ID 。)

(I'm just giving the IDs in the second case for sanity's sake.)

现在,让我可以使用此方法的唯一方法是创建一个空列表并遍历非 values_list()查询。

Right now the only way I can get this to work is to create an empty list and loop through the non-values_list() query.

for item in objects:
    ranked_items.append(item.content_object)

这只会产生 n 个查询,所以我我想知道是否有更好的方法。如标记所示,我使用的是PostgreSQL。

This just produces n queries, so I'm wondering if there's a better way. As shown by the tags, I'm using PostgreSQL.

推荐答案

这不是由Django引起的。您的数据库将按此顺序返回它们,因为未指定任何顺序。

This is not caused by Django; your database is returning them in this order since no ordering is specified.

这篇关于有没有一种方法可以使查询尊重输入参数的顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆