【发布时间】:2019-01-17 00:31:54
【问题描述】:
我的查询返回以下查询集:
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 中可能有很多不同的点击,所以我需要这个块尽可能高效
【问题讨论】:
标签: python-3.x django-queryset django-database django-q django-mysql