【问题标题】:How to efficiently use Django query and Q to filter each object in a queryset and return 1 field value for each unique field in the queryset如何有效地使用 Django 查询和 Q 过滤查询集中的每个对象并为查询集中的每个唯一字段返回 1 个字段值
【发布时间】: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


    【解决方案1】:

    阅读文档Generating aggregates for each item in a 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 function 可能会使用一个查询更有效的解决方案,但它需要一个高级数据库后端并且它无法工作,例如在使用 sqlite3 进行测试。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-05
      • 2023-01-16
      • 2014-03-22
      • 2016-07-20
      • 2013-10-10
      • 1970-01-01
      • 2019-09-05
      • 1970-01-01
      相关资源
      最近更新 更多