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.
What do you do after the Official Django Tutorial?
Here's what you'll learn:
- Start writing tests
- Increase the size / complexity of the Polls application.
- Learn how to code in Django by reading the Django source code.
- Finding code snippets to use in your website by reading the code of other websites.
- Deploying on Heroku and AWS.