Last active
May 1, 2020 07:45
-
-
Save manuganji/6056505 to your computer and use it in GitHub Desktop.
Aggregate query to know percentage of different types in a model
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.db.models import Count | |
from models import Animal | |
all_animal_types = Animal.objects.all().values('animal_type') | |
num_animal_types = len(all_animal_types) | |
dict_of_percentages = { animal_type['animal_type']:animal_type['animal_type__count'] * 100/num_animal_types | |
for animal_type in all_animal_types.annotate(Count('animal_type')) } | |
print dict_of_percentages | |
# output: | |
# { 'reptile': 49, 'bird':21, 'mammal':30} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.db import models | |
class Animal(models.Model): | |
animal_type_choices = ( | |
('reptile', 'reptile'), | |
('bird', 'bird'), | |
('mammal', 'Mammallian birds and Animals'), | |
('territorial', 'Land Animal'), | |
) | |
animal_type = models.CharField(choices=animal_type_choices, max_length=20, blank=True, null=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment