How to filter dates in django orm and get data of a specified date range / filter gte and lte

created at 07-17-2021 views: 2

In the actual application of Django, it is often necessary to extract the data within the specified date range from the data table. That must use gte/lte

Code demo:

General query

import datetime

start_date = datetime.date(2005, 1, 1)
end_date = datetime.date(2005, 3, 31)
article_obj= Article.objects.filter(pub_time__gte=start_date, pub_time__lte=end_date)

Use Q

from django.db.models import Q

article_obj= Article.objects.filter(Q(pub_time__gte=start_date), Q(pub_time__lte=end_date))
Please log in to leave a comment.