在字典中获取价格的平均值(Django JSONField)

huangapple go评论71阅读模式
英文:

Get mean value for price in dict (Django JSONField)

问题

I need to extract some products from orders with the same SKU number.

orders = Order.objects.filter(products__contains=[{"sku": "002-2-1"}])

for e in orders:
    print(e.products)

I need to find the mean value of "price."

I tried to get a single list with dictionaries:

a = sum(list(orders.values_list("products", flat=True)), [])

How can I find the mean value of price?

You can calculate the mean value of "price" using the following code:

import statistics

# Extract the prices from the list of dictionaries
prices = [float(product.get("price")) for product in a]

# Calculate the mean value of prices
mean_price = statistics.mean(prices)

There might be a better way to achieve this using Django's F expressions, but the provided code should work for your current setup.

英文:

I need to extract some products from orders with the same SKU number.

orders=Order.objects.filter(products__contains=[{"sku":"002-2-1"}])

for e in orders:
    print(e.products)

>>> [{'sku': 002-2-1, 'price': '366.00'}, {'sku': 002-2-1, 'price': '300.00'}] # 2 products in 1 order
>>> [{'sku': 002-2-1, 'price': '400.00'}]  # 1 product in the order

I need to find the mean value of "price"

I tried to get a one list with dicts:

a = sum(list(orders.values_list("products", flat=True)), [])

[{'sku': 002-2-1, 'price': '366.00'}, {'sku': 002-2-1, 'price': '300.00'}, {'sku': 002-2-1, 'price': '400.00'}]

How can I find the mean value of price?

[mean(e.get("price")) for e in a]

May be there is a better way to find it via F?

答案1

得分: 1

我没有尝试过但请尝试一下

```python
from django.db.models import Avg

order_qs = Order.objects.filter(products__contains=[{"sku": "002-2-1"}])
print(order_qs.aggregate(Avg("products__price")))

有趣的资源:
键、索引和路径转换 - 如何处理jsonfield查找
Avg - 用于聚合查询集以获取平均值的函数
条件聚合 - 有关如何使用Count或提到的Avg等函数进行聚合的一般信息

尽管您没有要求,但我想说一下:为什么要使用JSONField呢?在我看来,创建另一个名为Product的模型,并通过ForeignKey将其链接到Order更有意义。这还启用了所有Django的强大功能,如聚合、注释等等。特别是如果JSONField的结构始终相同...不创建进一步的模型有何意义呢?

我可以向您保证,使用专用的Product模型提供的解决方案会起作用。对于JSONField,我不是100%确定,告诉我一声!


<details>
<summary>英文:</summary>

I did not try it but please give this a try:

```python
from django.db.models import Avg

order_qs = Order.objects.filter(products__contains=[{&quot;sku&quot;:&quot;002-2-1&quot;}])
print(order_qs.aggregate(Avg(&quot;products__price&quot;)))

Interesting resources: <br>
Key, index, and path transforms - how to "deal" with jsonfield lookups <br>
Avg - the function you want to aggregate your queryset with to get the mean value <br>
Conditional Aggregating - general "how-to" how to aggregate with functions like Count or mentioned Avg

Even though you did not ask for a potentially better way I want to say: "Why are you using a JSONField?". In my eyes creating another model called Product and link it via a ForeignKey to Order makes much more sense. It also enables all the cool django features like aggregating, annotating and so much more. Especially if the scheme of the JSONField is always the same... what's the point in not creating a further model?

I can guarantee you that with a dedicated Product model the provided solution is going to work. With a JSONField I am not 100% sure - let me know!

huangapple
  • 本文由 发表于 2023年7月20日 17:38:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/76728562.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定