我想要我的(预订类型)计数,我有 3 种类型的选择(模型中的选择字段)个人、团体和证书。
d1 = Booking.objects.values('booking_type').annotate(booking_count=Count('booking_type'))
{f.get('booking_type'): f.get('booking_count') for f in d1}
下面是上面的输出:但是为什么代码没有给我证书计数
{'团体': 2, '个人': 3}
我也更改了要过滤的值,但是没有任何效果。
最佳答案
But why the code Will Cant give me the Count of Certificate.
因为该计数为零,并且数据库在封闭世界假设下工作。因此它不知道这些值存在。
您可能需要添加 .order_by(..)
来强制 Django 执行 GROUP BY
。此外,我们可以使用选项
为这些项目添加零:
d1 = Booking.objects.values('booking_type').annotate(
booking_count=Count('booking_type')
)<b>.order_by('booking_type')</b>
result = {f['booking_type']: f['booking_count'] for f in d1}
for c in Booking._meta.get_field('booking_type').choices:
result.<b>setdefault(c[0], 0)</b>
关于python - 在 django 映射中如何获取选择字段的完整计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58206432/