簡體   English   中英

按 ID 獲取多行的最快方法,順序不變

[英]Fastest way to fetch multiple rows by ID, with ordering intact

我需要根據主鍵的順序列表從Product表中查找和獲取信息。

pks = [22,51,22,45]
products = list(Products.object.filter(pk__in=pks).values_list("pk", flat=True))
# products order is not same as pks's order.


# one solution is to put them into a mapping of sorts
products_by_id = {
prod.pk : prod for prod in Products.object.filter(pk__in=pks)
}
ordered_prods = [products_by_id[pk] for pk in pks]

使用 Djano ORM 有更好或更快的方法嗎?

Products.object.filter(pk__in=pks).order_by(lambda p: ...pk.find[p.id])

https://gist.github.com/cpjolicoeur/3590737?permalink_comment_id=2202866#gistcomment-2202866

這似乎正是我要找的。

SELECT * FROM foo WHERE id IN (3, 1, 2) ORDER BY array_position(ARRAY[3, 1, 2], id);

可能以某種方式將extra()與 array_position 一起使用嗎?

有了ORM,可以用array_position function注解,然后按注解字段排序:

Products.objects.filter(
    pk__in=pks
).annotate(
    _array_order=Func(
        Value(pks),
        F("pk"),
        function="array_position",
    )
).order_by(
    "_array_order"
)

但是,在許多情況下,從 QuerySet 轉換為列表並使用 python 代碼進行排序也應該沒問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM