You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django:如何从关联模型的QuerySet中提取仅价格数据?

提取Django分类关联的支出价格数据

根据你的模型结构,以下几种方式可以提取分类对应的价格数据:

1. 提取所有支出的价格列表

如果不需要按分类分组,直接从Outlay QuerySet中提取价格:

# 获取所有价格的扁平列表
prices = Outlay.objects.values_list('price', flat=True)
# 结果示例:<QuerySet [Decimal('175.00'), Decimal('232.00')]>

如果需要同时关联分类信息,返回包含分类名和价格的字典列表:

category_price_pairs = Outlay.objects.values('category__name', 'price')
# 结果示例:<QuerySet [{'category__name': '食材', 'price': Decimal('175.00')}, ...]>

2. 按分类分组,获取每个分类对应的所有价格

方法一:通过Category QuerySet预取关联数据后遍历

先预取每个分类对应的支出记录,再遍历提取价格:

from collections import defaultdict

# 预取分类关联的支出数据,减少数据库查询
categories = Category.objects.prefetch_related('outlay_set')
category_price_map = defaultdict(list)

for category in categories:
    # 提取当前分类下所有支出的价格
    category_price_map[category.name] = [outlay.price for outlay in category.outlay_set.all()]

# 结果示例:{'食材': [Decimal('175.00')], '酒水': [Decimal('232.00')]}

方法二:使用数据库聚合(需PostgreSQL支持)

利用ArrayAgg聚合函数直接从数据库层面按分类分组获取价格数组:

from django.db.models import ArrayAgg

category_prices = Category.objects.annotate(
    # 聚合当前分类下所有支出的价格
    prices=ArrayAgg('outlay_set__price')
).values('name', 'prices')

# 结果示例:<QuerySet [{'name': '食材', 'prices': [Decimal('175.00')]}, ...]>

如果已经有你提到的queryset = Outlay.objects.all().prefetch_related('category'),可以直接遍历提取:

# 提取所有价格
prices = [outlay.price for outlay in queryset]

# 按分类分组整理
category_price_map = {}
for outlay in queryset:
    category_name = outlay.category.name if outlay.category else '无分类'
    if category_name not in category_price_map:
        category_price_map[category_name] = []
    category_price_map[category_name].append(outlay.price)

内容的提问来源于stack exchange,提问作者Michael_Brock

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 08:35:23