Home >Backend Development >Python Tutorial >How to Filter Django Objects by a Date Range?

How to Filter Django Objects by a Date Range?

Susan Sarandon
Susan SarandonOriginal
2024-11-04 12:53:29509browse

How to Filter Django Objects by a Date Range?

Filtering Query Objects by Date Range in Django

When working with Django models that contain date fields, it often becomes necessary to filter objects based on a specified date range. This allows you to retrieve only those objects that fall within a specific time period.

Problem:

Consider the following model with a date field:

<code class="python">class Sample(models.Model):
    date = fields.DateField(auto_now=False)</code>

How can you filter the objects of this model to only include those with dates between 1-Jan-2011 and 31-Jan-2011?

Solution:

To filter objects by a date range, use the range filter in combination with the field you wish to filter:

<code class="python">Sample.objects.filter(date__range=["2011-01-01", "2011-01-31"])</code>

Alternative for Month-Wise Filtering:

If you only need to filter objects based on the month, you can use the following syntax:

<code class="python">Sample.objects.filter(date__year='2011',
                      date__month='01')</code>

Excluding Range Ends:

If you wish to exclude the specified range ends, consider using gt (greater-than) and lt (less-than) filters as suggested by Bernhard Vallant in the edit:

<code class="python">Sample.objects.filter(date__gt="2011-01-01",
                      date__lt="2011-01-31")</code>

The above is the detailed content of How to Filter Django Objects by a Date Range?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn