有没有一种方法可以使查询尊重输入参数的顺序?

编程入门 行业动态 更新时间:2024-10-23 07:18:31
本文介绍了有没有一种方法可以使查询尊重输入参数的顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

这个故事有两个模型,分别是 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.

更多推荐

有没有一种方法可以使查询尊重输入参数的顺序?

本文发布于:2023-10-26 23:28:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1531656.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:顺序   参数   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!