简体   繁体   中英

In django mapping how to get complete count of choice filed

I want the Count of my (Booking Type) I have 3 types of choices (choice field in Model) Individual, Group, and Certificate.

d1 = Booking.objects.values('booking_type').annotate(booking_count=Count('booking_type'))
{f.get('booking_type'): f.get('booking_count') for f in d1}

Below is the output of the above: However Why does the code not give me the Count of Certificate

{'GROUP': 2, 'INDIVIDUAL': 3}

I changed the values to filter too, however nothing works.

But why the code Will Cant give me the Count of Certificate.

Because that count is zero, and since a database works under the closed world assumption . It thus does not know these values exists.

You probably need to add a .order_by(..) to force Django to perform a GROUP BY . Furthermore we can use the choices to add zeros to these items:

d1 = Booking.objects.values('booking_type').annotate(
    booking_count=Count('booking_type')
)
result = {f['booking_type']: f['booking_count'] for f in d1}

for c in Booking._meta.get_field('booking_type').choices:
    result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM