-1
我有這樣的表如何分組並按每組返回值?
id p_id number
1 1 12
2 1 13
3 2 14
4 2 15
如何獲得在我看來這樣的項目, 我用的p_id意味着組和從組
for p_id 1 returns count 2 and 12,13
for p_id 2 returns count 2 and 14,15
我有這樣的表如何分組並按每組返回值?
id p_id number
1 1 12
2 1 13
3 2 14
4 2 15
如何獲得在我看來這樣的項目, 我用的p_id意味着組和從組
for p_id 1 returns count 2 and 12,13
for p_id 2 returns count 2 and 14,15
您可以使用values()
和annotate()
到組獲得數值,所以:
from django.db.models import Count
pid_group = YourModel.objects.values('p_id').annotate(ncount=Count('number'))
後,你會得到類型的字典pid_group
就像個列表是:
[{'p_id': 1, 'ncount': 2}, {'p_id': 2, 'ncount': 2}]
你可以得到的數值容易然後:
for pid in pid_group:
number_values = YourModel.objects.filter(p_id=pid.get('p_id'))
希望它能幫助。
不錯,但可能更有效地獲取對象並將其分組在內存中。 – Marcin