Django complex queries
I need to craft a filter for an object that checks date ran开发者_如何学Goges. Right now I'm performing a very inefficient loop which checks all the objects. I would like to simplify this to a database call.
The logic is you have a start
and an end
date objects. I need to check if the start OR the end is within the range of an appointment.
if (start >= appointment.start && start < appointment.end) ||
(end > appointment.start && end <= appointment.end)
I could do this in SQL, but I'm not as familiar with the Django model structure for more complex queries.
You need Q objects for & and OR operators and the range
field lookup type
Q Object: http://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects
range: http://docs.djangoproject.com/en/dev/ref/models/querysets/#range
Entry.objects.filter(Q(start__range=(appointment.start, appointment.end)) |
Q(end__range=(appointment.start, appointment.end)))
If an SQL BETWEEN
, is not what you are looking for, you can always use specific combinations of Q objects to reproduce your conditions exactly:
Entry.objects.filter((Q(start__gte=appointment.start) & Q(start__lt=appointment.end)) |
(Q(end__gt=appointment.start) & Q(end__lte=appointment.end)))
精彩评论