[英]django filter by datetime on a range of dates
I have a model with field "created_at", and I have a list of dates.我有一个带有字段“created_at”的 model,并且我有一个日期列表。 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 __gte
(greater than or equal) and __lte
(less than or equal).您可以使用
__gte
(大于或等于)和__lte
(小于或等于)。 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 queryset.filter(created_at__range=(start_date, end_date)) 这将导致问题,即结束日期将是排他性的让我们举个例子 sql 如何将此查询视为
created_at >= "start_date 00:00:00" AND created_at <= "end_date 00:00:00"
所以最好的解决方案是将最大时间添加到结束日期,即 "23:59:59" 所以它会created_at >= "start_date 00:00:00" AND created_at <= "end_date 23:59:59"
所以你可以通过做
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此外,如果将 1 添加到结束日期,这将是错误的方法,因为结束日期将为 end_date+1 00:00:00,因此查询还将包括 end_date+1 00:00:00,这是错误的
there is another answer for this we can change the datetimefield to datefield还有另一个答案,我们可以将 datetimefield 更改为 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) )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.