Django聚合和跟随外键关系 [英] Django aggregation and following foreign key relations
本文介绍了Django聚合和跟随外键关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
模型:
class Item(models.Model):
name = models.CharField(max_length=100)
# More stuff.
class Sale(models.Model):
sale_date = models.DateField(auto_now_add=True)
item = models.ForeignKey(Item)
# More stuff.
查看:
class TodaySales(ListView):
# Stuff in here.
def get_queryset(self):
sales_today = Sale.objects.filter(sale_date=date.today())
return sales_today.values('item').annotate(Count('item'))
我收回了这样一个例子:
I get back something like this:
[{'item': 1, 'item__count': 2}, {'item': 2, 'item__count': 1}]
这是很好的,所有,但我真正想要的是能够获得关于项目的额外信息,如其名称等但是我似乎不能这么容易,因为我得到的是项目ID,所以我不能在我的模板中,例如{{item.name}}。
This is nice and all and but what I really want is to be able to get extra information about the item, such as its name, etc. But I can't seem to do this easily since all I get is the item ID, so I can't in my template do, for example, {{ item.name }}.
有没有一些很好的方法?
Is there some good way of doing this?
推荐答案
这样做。尝试:
Item.objects.filter(
sale__sale_date=date.today()
).annotate(
count = Count('sale')
)
这篇关于Django聚合和跟随外键关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文