Select between two dates with Django

PythonDjango

Python Problem Overview


I am looking to make a query that selects between dates with Django.

I know how to do this with raw SQL pretty easily, but how could this be achieved using the Django ORM?

This is where I want to add the between dates of 30 days in my query:

start_date = datetime.datetime.now() + datetime.timedelta(-30)
context[self.varname] = self.model._default_manager.filter(
    current_issue__isnull=True
    ).live().order_by('-created_at')

Python Solutions


Solution 1 - Python

Use the __range operator:

...filter(current_issue__isnull=True, created_at__range=(start_date, end_date))

Solution 2 - Python

Solution 3 - Python

If you are using a DateTimeField, Filtering with dates won’t include items on the last day.

You need to casts the value as date:

...filter(created_at__date__range=(start_date, end_date))

Solution 4 - Python

two methods

.filter(created_at__range=[from_date, to_date])

another method

.filter(Q(created_at__gte=from_date)&Q(created_at__lte=to_date))
  • gte means greater than equal
  • lte means less than equal

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJeff TaggartyView Question on Stackoverflow
Solution 1 - PythonDaniel RosemanView Answer on Stackoverflow
Solution 2 - PythonIgnacio Vazquez-AbramsView Answer on Stackoverflow
Solution 3 - PythonsuhailvsView Answer on Stackoverflow
Solution 4 - PythonManjuanth V MView Answer on Stackoverflow