I have a Restaurant model, and Schedule model which has a foreign key relationship to Restaurant. I am currently trying to query restaurants that are open right now. So far I have been doing
qs = Restaurant.objects.all()
qss = []
for q in qs:
schedule = q.schedule_set.filter(start_hour__lte=currHour, end_hour__gte=currHour)
if schedule:
qss.append(q)
where currHour is current hour given by datetime.now().
But I am wondering if I can rewrite this query with Q, so that if I have to combine this query with other queries, I can just add more queries to q = Q(), for example.
You shouldn't do this iteration over queryset items when you can actually write a query for the whole thing. The way you have it set up now, you're issuing a DB query for each iteration. If I understand your scenario right, you can rewrite it like this to issue just one query, using ForeignKey traversal:
qss = Restaurant.objects.filter(schedule__start_hour__lte=currHour, schedule__end_hour__gte=currHour)
Then you can add queries to this as well. filter()
is chain-able, so you can also do things like:
q = Model.objects.filter(**filter_kwargs)
q = q.filter(**additional_filter_kwargs)