I have a model with 2 datetime fields which looks like this:
class Booking(models.Model):
start_date = models.DateTimeField()
end_date = models.DateTimeField()
...
As test data I have 2 bookings with start_date before 17:30 and 2 bookings after 17:45, all on the same day (8 May 2018). I am trying to filter the bookings with the __time lookup to find all the bookings before (and including) 17:30. My queryset is:
bookings = Booking.objects.filter(date__time__lte=datetime.time())
Where datetime.time prints as
datetime.time(17, 30)
and where the date part of the datetime is the same as the bookings dates. The above query is returning an empty queryset but if I use the same query except filtering for times greater than datetime.time() i.e.
bookings = Booking.objects.filter(date__time__gte=datetime.time())
The queryset returns all the bookings (where it should only return the 2 bookings with start_date after 17:30). Can someone please explain to me how the __time lookup is meant to be used?
EDIT I updated the filter to
bookings = Booking.objects.filter(start_date__time__lte=datetime.time())
and the result is the same. When I print the values of the bookings, the values are:
print Booking.objects.all().values('date', 'end_date')
[
{'start_date': datetime.datetime(2018, 5, 8, 16, 30, tzinfo=<DstTzInfo 'Africa/Harare' CAT+2:00:00 STD>), 'end_date': datetime.datetime(2018, 5, 8, 17, 0, tzinfo=<DstTzInfo 'Africa/Harare' CAT+2:00:00 STD>)},
{'start_date': datetime.datetime(2018, 5, 8, 17, 0, tzinfo=<DstTzInfo 'Africa/Harare' CAT+2:00:00 STD>), 'end_date': datetime.datetime(2018, 5, 8, 17, 30, tzinfo=<DstTzInfo 'Africa/Harare' CAT+2:00:00 STD>)},
{'start_date': datetime.datetime(2018, 5, 8, 17, 45, tzinfo=<DstTzInfo 'Africa/Harare' CAT+2:00:00 STD>), 'end_date': datetime.datetime(2018, 5, 8, 18, 15, tzinfo=<DstTzInfo 'Africa/Harare' CAT+2:00:00 STD>)},
{'start_date': datetime.datetime(2018, 5, 8, 17, 45, tzinfo=<DstTzInfo 'Africa/Harare' CAT+2:00:00 STD>), 'end_date': datetime.datetime(2018, 5, 8, 18, 15, tzinfo=<DstTzInfo 'Africa/Harare' CAT+2:00:00 STD>)}
]
EDIT 2 I forgot to mention I need to get the bookings that are on the same date. As siddhant0905 suggested I filtered the queryset with datetimes instead and added an extra filter to make sure it was on the same date. The following worked for me:
bookings = Booking.objects.filter(Q(start_date__date=datetime.date()) & Q(start_date__lte=datetime))