0

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,863
  • 5
  • 28
  • 51
  • see if this [SO Q/A](http://stackoverflow.com/questions/16016002/django-how-to-get-a-time-difference-from-the-time-post) helps – Pynchia Jun 10 '15 at 07:21
  • `User.objects.select(profile__birthdate__gt=...)`, see https://docs.djangoproject.com/en/1.8/topics/db/queries/#lookups-that-span-relationships – Andrea Corbellini Jun 10 '15 at 07:26

1 Answers1

3
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.

Community
  • 1
  • 1
f43d65
  • 2,264
  • 11
  • 15