Home  >  Article  >  Backend Development  >  How to Filter Django Query Objects by Date Range?

How to Filter Django Query Objects by Date Range?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-04 00:27:03281browse

How to Filter Django Query Objects by Date Range?

Filtering Django Query Objects by Date Range

When working with Django models, filtering query objects by date range is a common task. To achieve this, you can utilize Django's built-in date range functionality.

Let's consider a model similar to the one mentioned in the question:

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

Suppose you need to filter objects that fall within a specific date range, such as those with dates between January 1, 2011, and January 31, 2011. Here's how you can do it:

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

This query uses the __range lookup to specify the date range within which the date field of Sample objects should fall.

Alternatively, if you want to filter objects month-wise, you can use the following syntax:

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

This query filters all objects with dates in January 2011.

Excluding Range Ends

Note that the above queries include the range ends (i.e., January 1 and January 31, 2011, in the first example). If you need to exclude these range ends, you can use the __gt (greater-than) and __lt (less-than) lookups, as suggested by Bernhard Vallant in the answer's edit:

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

This query filters all objects with dates greater than January 1, 2011, and less than January 31, 2011, effectively excluding the range ends.

The above is the detailed content of How to Filter Django Query Objects by 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
Previous article:Mocks, what are they?Next article:Mocks, what are they?