Django计数相关对象 [英] Django count related objects
本文介绍了Django计数相关对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何计算Django中的相关对象(少于
How can I count related objects in Django (in less than N queries, where N is number of object).
为了弄清楚,假设我有表 A 和 B 。每个 B 连接到正好一个 A 。方法我试过:
To clarify, let's say I have tables A and B. Every B is connected to exactly one A. Approach I tried:
A.objects.select_related().filter(attr=val)
A[i].B_set.count()
当然,对于每个 A [i] 我想找出一个 B 对象的数量Django执行一个查询。
Of course, for every A[i] I want to find out number of B objects Django executes one query.
所以问题是 - 有没有办法优化?
So the question is - is there a way to optimize that?
推荐答案
没有尝试执行多少个查询,但是djano的方式应该使用 annotate()
如下:
Have not tried how many queries are executed, but the djano way should be using annotate()
something like:
q = A.objects.select_related().annotate(num_B=Count('B'))
print A[0].num_B
这篇关于Django计数相关对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文