2👍
✅
from django.db import models
aggregates = {
'have_x_many_males': models.Sum(models.Case(models.When(is_male=True, then=1), output_field = models.IntegerField())),
'have_x_many_roberts': models.Sum(models.Case(models.When(last_name_id='robert', then=1), output_field = models.IntegerField())),
}
queryset = Person.objects.all().annotate(**aggregates)
👤serg
-1👍
class Person(models.Model):
is_asian = models.BooleanField()
is_male = models.BooleanField()
is_gay = models.BooleanField()
last_name = models.ForeignKey('FamilyName')
is_happy = models.BooleanField()
def get_count(self):
return{
'have_x_many_males': Person.objects.filter(is_male=True).count()
'have_x_many_gays': Person.objects.filter(is_gay=True).count()
'have_x_many_robertss': Person.objects.filter(last_name_id='robert').count()
}
Then do p = Person.objects.all().get_count()
👤Yax
- Defining models when using multiple databases
- How to use reverse an url with extra arguments in a django template tag?
Source:stackexchange.com