我有返回以下查询集的查询:
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
所以我需要这个块尽可能高效