I have a model with field "created_at", and I have a list of dates. So, I want to get all the models that are created in the date range. How?
I know that we can compare datetime and date easily using:
queryset.filter(created_at__startswith=date)
But, I have a range of dates, so how?
Let me know for more information.
You can use range lookup. Just find the lowest and greater date and then apply it as:
queryset.filter(created_at__range=(start_date, end_date))
You can use range eg
import datetime
first_date = datetime.date(2005, 1, 1)
last_date = datetime.date(2005, 3, 31)
queryset.filter(created_at__range=(first_date, last_date))
You can use __gte
(greater than or equal) and __lte
(less than or equal). For example:
queryset.filter(created_at__gte=datetime.date.today())
queryset.filter(created_at__range=(start_date, end_date)) this will lead to problem which is the end date will be exlusive let take example how will the sql will look to this query as created_at >= "start_date 00:00:00" AND created_at <= "end_date 00:00:00"
so the best solution is to add max time in date to the end date which is "23:59:59" so it will created_at >= "start_date 00:00:00" AND created_at <= "end_date 23:59:59"
so you can a achieve this by doing
import datetime
queryset.filter(created_at__range=(
datetime.datetime.combine(start_date, datetime.time.min),
datetime.datetime.combine(end_date, datetime.time.max),
))
also if adding 1 to end date this will be wrong approach because the end date will be end_date+1 00:00:00 so the query will include also the end_date+1 00:00:00 which is wrong
there is another answer for this we can change the datetimefield to datefield
queryset.annotate(Date = Cast('created_at', DateField())).filter(Date__range=(start_date,end_date))
and there is another answers you play around with it like
queryset.filter(Q(created_at__range=(start_date,end_date)) | Q(created_at__icontains=end_date) )
OR
queryset.filter(Q(created_at__range=(start_date,end_date)) | Q(created_at__startswith=end_date) )
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.