Django查询集中字母“r”的计数

omqzjyyz  于 2023-02-17  发布在  Go
关注(0)|答案(2)|浏览(81)

我需要计算查询集中字段“wertung”中的所有“r“。
“right = protokoll.filter(wertung__contains ='r').count()”-对包含一个“r”的字段进行计数-不管是一个“r”还是两个“rr”,但现在我需要对所有“r“进行计数。

igetnqfo

igetnqfo1#

要统计查询集中所有记录中“wertung”字段中字母“r”的所有出现次数,可以将annotate()函数与Count()函数结合使用。

from django.db.models import Count, Sum, Q

r_count = Protokoll.objects.annotate(r_count=Count('wertung', filter=Q(wertung__contains='r'))).aggregate(total_r_count=Sum('r_count'))['total_r_count']

有关参考,请参见here

06odsfpq

06odsfpq2#

我将从包含'r'的字段中获取数据,然后用Python生成计数。

data = protokoll.filter(wertung__contains ='r').values_list('wertung', flat=True)
r_count = 0
for value in data:
    r_count += value.count('r')

相关问题