有没有办法让查询尊重输入参数的顺序?
(如果这完全荒谬,请告诉我,这可能是我没有找到任何相关内容的原因。)
这个故事有两个模型 Ranking
和 Artist
、Ranking
一般与 Artist
相关(object_id、content_type...整个 shebang)。
我有一个由 Ranking.objects.values_list()
返回的对象列表,按特定字段排序(在我的例子中是 score
)。显然,如果我想显示已排名的艺术家列表,我希望它们按相同的顺序排列。我尝试了不同的方法,例如 .filter(pk__in=list)
、.in_bulk(list)
等。尝试强制 .values_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。)
现在,我可以让它工作的唯一方法是创建一个空列表并循环遍历非 values_list()
查询。
for item in objects:
ranked_items.append(item.content_object)
这只会产生 n 个查询,所以我想知道是否有更好的方法。如标签所示,我正在使用 PostgreSQL。
(Please let me know if this is completely absurd, that is probably a reason why I haven't found anything on this.)
This story has two models Ranking
and Artist
, Ranking
is generically related to Artist
(object_id, content_type... the whole shebang).
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]
And return it like so:
>>> 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]
(I'm just giving the IDs in the second case for sanity's sake.)
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)
This just produces n
queries, so I'm wondering if there's a better way. As shown by the tags, I'm using PostgreSQL.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这不是 Django 造成的;由于未指定顺序,您的数据库将按此顺序返回它们。
This is not caused by Django; your database is returning them in this order since no ordering is specified.