Are you getting validation errors when you try to filter a DateTimeField by today’s date?
It can be a huge pain, when, you can’t for the life of you get Django to filter correctly on today’s date.
There is one, simple way of solving this problem.
Once you understand how to do this, you’ll laugh at how easy it was to implement.
Let’s say, for example, that you have a column in a model called post_date.
class MyModel(models.Model): post_date = models.DateTimeField(auto_add_now=True) # ... additional fields ...
How do you filter DateTimeField by today’s date?
The problem is that you have is that you need today’s posts, but it’s tough because, you’re model is implemented as a DateTimeField. You need to match the actual date. In order to do that you need to match the year, month and day explicitly.
from datetime import date today = date.today() today_filter = MyModel.filter(post_date__year=today.year, post_date__month=today.month, post_date__day=today.day)
But that’s too much typing!
You might think this is way to much to type every time you want want to filter records by date. Are there some things that you can do to make this easier?
Sure! You can create a helper function.
def filter_by_date(date): return MyModel.filter(post_date__year=date.year, post_date__month=date.month, post_date__day=date.day)
Or, you can upgrade your instance of Django to 1.9 where there is a filter specifically for dates.
from datetime import date MyModel.filter(post_date__date=date.today())
The choice is yours! But, now you know exactly what you need to do to filter by date.
Similar PostsWhat do you do when 'makemigrations' is telling you About your Lack of Default Value
How to Implement Many-To-Many Relationship in Django
Test your Queries before they make it into Production using the Django Shell
I have a ChoiceField Callable that Includes a Queryset but it Breaks my Django app
Simple Method of Updating Models with ModelForms
Need help with Django REST Framework? Django REST Framework documentation a little confusing?
Join me for my FREE Django REST Framework email course:
Django REST Framework Email Course
You'll get 1 lesson everyday for 7 days.
- Request Methods
- Basic Authentication
- JQuery Integration
- AngularJS Integration