Skip to content

Instantly share code, notes, and snippets.

@manuganji
Last active May 1, 2020 07:45
Show Gist options
  • Save manuganji/6056505 to your computer and use it in GitHub Desktop.
Save manuganji/6056505 to your computer and use it in GitHub Desktop.
Aggregate query to know percentage of different types in a model
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}
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