我有这个数据结构:
class Currency(Model):
name = CharField()
...
class Invoice(Model):
currency = ForeignKey(Currency)
...
我想按Invoices
过滤所有Currencies
个分组。我希望结果是这样的:
{
'USD': '<INVOICES_QUERYSET_FOR_USD>',
'EUR': '<INVOICES_QUERYSET_FOR_EUR>',
...
}
有没有简单的方法来实现这一点,还是我必须自己安装字典?我知道Annotate
给出了类似的结果,但我只是想用一个公共属性值对Queryset进行分组。
答案 0 :(得分:1)
这样的东西可以让你得到你想要的东西。
from collections import defaultdict
currencies_of_interest = [ 'USD', 'EUR', ]
qs = Invoice.objects.select_related(
'currency'
).filter(
currency__name__in = currencies_of_interest
)order_by('currency__name')
currencies = defaultdict(list)
for x in qs:
currencies[x.currency.name].append(x)
# now currencies will look like:
# {
# 'USD': list[Invoice] for USD,
# 'EUR': list[Invoice] for EUR,
# ...
# }
如果您更喜欢使用查询集,并且不介意对数据库进行多次查询:
currencies_of_interest = [ 'USD', 'EUR', ]
currencies = {}
for x in currencies_of_interest:
currencies[x] = Invoice.objects.select_related(
'currency').filter(currency__name=x)
# now currencies will look like:
# {
# 'USD': QuerySet[Invoice] for USD,
# 'EUR': QuerySet[Invoice] for EUR,
# ...
# }