英文:
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=[{"sku":"002-2-1"}])
print(order_qs.aggregate(Avg("products__price")))
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!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论