简体   繁体   中英

django filter by datetime on a range of dates

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__date__range=(start_date, end_date))

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) )

使用https://pypi.python.org/pypi/django-daterange-filter/使用日期范围过滤器。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM