如何在Django中按日期范围过滤请求对象?

2uluyalo  于 2023-10-21  发布在  Go
关注(0)|答案(1)|浏览(108)

我有一个这样的循环函数:

saved_date = request.GET.get('date')
start_date = request.GET.get('start_date')
end_date = request.GET.get('end_date')

if saved_date is not None:
   queryset = Contact.objects.filter(
       createdAt__istartswith=saved_date).values_list('phone', flat=True)
elif start_date and end_date is not None:
   queryset = Contact.objects.filter(
       createdAt__range=[start_date, end_date]).values_list('phone', flat=True)

因此,我需要按日期范围过滤对象,包括 * 结束日期 *。如何过滤日期在 start_dateend_date 之间的所有对象?

rkue9o1l

rkue9o1l1#

如果您已经在**Contact模型中将createdAt当作DateTimeField**,请尝试此代码

if saved_date is not None and (start_date is None and end_date is None) :
   queryset = Contact.objects.filter(
       createdAt__date__istartswith=saved_date).values_list('phone', flat=True)
elif saved_date is None and (start_date is not None and end_date is not None):
   queryset = Contact.objects.filter(
       createdAt__date__range=[start_date, end_date]).values_list('phone', flat=True)

相关问题