How to count users in JOINed models?

83 views Asked by At

Let's say, we have two models:

class User(models.Model):
    nickname = models.CharField(max_length=50)
    email = models.CharField(max_length=50)

class Profile(models.Model):
    user = models.OneToOneField(User, primary_key=True)
    carma = models.BooleanField(default=False)
    birthdate = models.DateField(input_formats=['%Y-%m-%d'])

How to get amount of users where:

1) all users with ages below 18?

2) all users between 18 - 25

3) all users above 25

As I understood, I need to get an age from birthdate, e.g. this way:

 def age(self):
        import datetime
        return int((datetime.date.today() - self.birthday).days / 365.25  )

and use returned age in query somehow.

How to perform these cross-requests with function inside (for each specified query) in Django?

Thank you!

1

There are 1 answers

0
f43d65 On BEST ANSWER
from datetime import date

def add_years(d, years):
    try:
        return d.replace(year = d.year + years)
    except ValueError:
        return d + (date(d.year + years, 1, 1) - date(d.year, 1, 1))

today = datetime.date.today()
ago18 = add_years(today, -18)
ago25 = add_years(today, -25)

# < 18
User.objects.filter(profile__birthdate__gt=ago18)
# 18 <= and < 25
User.objects.filter(profile__birthdate__lte=ago18, profile__birthdate__gt=ago25)
# 25 <=
User.objects.filter(profile__birthdate__lte=ago25)

Based on this answer.