Jacob
Jacob

Reputation: 3

Django Date Filter Weirdness

I have some date filtering in django that I just can't see what's wrong.

I have a model with this field:

date_of_birth = models.DateField(blank = True, null=True, auto_now=False, auto_now_add=False)

I then select all data

users = UserDetails.objects.all()

I have 2 rows in the database and two object returned

>>> users
[<UserDetails: UserDetails object>, <UserDetails: UserDetails object>]

>>> users[0]
<UserDetails: UserDetails object>

I can see each objects date_of_birth value

>>> users[0].date_of_birth
datetime.date(1971, 9, 28)

However any filter I try always fails?

>>> users = users.filter(date_of_birth__year >= 1970)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
NameError: name 'date_of_birth__year' is not defined

>>> users = users.filter(date_of_birth == datetime.date(1971, 9, 28))
Traceback (most recent call last):
  File "<console>", line 1, in <module>
NameError: name 'date_of_birth' is not defined

>>> users = users.filter(date_of_birth == '1971-09-28')
Traceback (most recent call last):
  File "<console>", line 1, in <module>
NameError: name 'date_of_birth' is not defined

Can anyone help explain what's wrong here?
I'm at a loss.

Thanks.

Upvotes: 0

Views: 1794

Answers (1)

mipadi
mipadi

Reputation: 410662

You don't filter using the comparison operators. What you're doing is actually passing a keyword argument to the filter method. To filter based on equality, simply do:

users = users.filter(date_of_birth=datetime.date(1971, 9, 28))

To filter using greater than or equals, use:

users = users.filter(date_of_birth__year__gte=1970)

That is, you append __gte to the keyword argument.

You can also filter on less than or equals (date_of_birth__year__lte), less than (date_of_birth__year__lt), or greater than (date_of_birth__year__gt).

Upvotes: 3

Related Questions