0

我有返回以下查询集的查询:

results = <QuerySet [<Product: ItemA>, <Product: ItemA>, <Product: ItemB>, <Product: ItemB>, <Product: ItemB>, <Product: ItemC>, <Product: ItemC>]>

模型的__str__表示是name并且每个Product变体可能具有不同的price字段值。在这个查询之后,我需要在我的数据库中搜索查询Product集中的每个,并返回每个唯一的最低价格,name例如:

Lowest price for all in database where name is == to ItemA
Lowest price for all in database where name is == to ItemB
Lowest price for all in database where name is == to ItemC

我使用下面的代码块来实现这个目标:

query_list = []
for each in results:
    if each.name not in query_list:   #Checks if the name of the object is not in in the query list
        query_list.append(each.name)   #Adds just the name of the objects so there is just one of each name in query_list

for each in query_list:
    priced = results.filter(name=each).order_by('price').first()  #Lowest price for each name in query_list

这种感觉非常低效。有没有一种方法可以进行类似的计算,而不必将每个列表的唯一名称附加Product到单独的列表中,并遍历该列表,然后为每个列表进行查询?我觉得有一种方法可以使用一种复杂的查找来实现我的目标,也许事件使用更少的 Python,并使数据库做更多的工作,但以上是我能弄清楚的最好的远的。可能有很多不同的命中,results所以我需要这个块尽可能高效

4

1 回答 1

0

阅读文档后很容易为 QuerySet 中的每个项目生成聚合以及“与默认排序或 order_by() 的交互”。

from django.db.models import Min

prices = {x['name']: x['lowest_price']
          for x in results.values('name').annotate(lowest_price=Min('price').order_by()}

for product in results:
    if product.name in prices and product.price == prices[product.name]:
        priced = row  # output the row
        del prices[product.name]

这由两个数据库查询运行。

使用Window 函数可能可以使用一个查询更有效的解决方案,但它需要一个高级数据库后端,并且它不能在使用 sqlite3 的测试中工作。

于 2018-08-10T02:32:58.047 回答