[Fixed]-Count the number of occurrences of certain choices in models

0👍

I was able to find some Django docs about Conditional Aggregation that helped me solve this.

def most_specifics():
    reverse_specs = dict((v, k) for k, v in Award.specific_choices)
    return Team.objects.annotate(
        c=Sum(
            Case(
                When(award__award_type__in=reverse_specs.values(), then=1),
                default=0,
                output_field=PositiveSmallIntegerField(),
            )
        )
    ).order_by('-c')

1👍

choices = Award.specific_choices.all()

c = Team.objects.filter(award__award_type__in=choices).count()

0👍

Following code will find number of choices in certain field of a given model:

my_field=Model._meta.get_field('field_name')

length=len(my_field.choices._display_map)
👤Amrit

Leave a comment