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.
You don’t filter using the comparison operators. What you’re doing is actually passing a keyword argument to the
filtermethod. To filter based on equality, simply do:To filter using greater than or equals, use:
That is, you append
__gteto 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).