setchock setchock - 5 months ago 19
Python Question

Django: how to query relations effectively

I have a model "Booking" referencing to another model "Event" with a foreign key.

class Event(models.Model):
title = models.CharField(_("title"), max_length=100)

class Booking(models.Model):
user = models.ForeignKey('auth.User', ..., related_name='bookings')
event = models.ForeignKey('Event', ..., related_name='bookings')

I want to get all the events a user has booked in a set, to use it in a ListView.

I have managed to accomplish that by overwriting ListView's get_queryset method:

def get_queryset(self):
user_bookings = Booking.objects.filter(user=self.request.user)
events = Event.objects.filter(id__in=user_bookings.values('event_id'))
return events

But I am quite sure, that that is not a very efficient way of solving my problem, in terms of needed database queries.

I have thought about using "select_related" method, but I didn't figured out how I could benefit from that in my usecase.

My question is: How would you solve this? What is the most efficient way to do something like this?


You can do this in one line: Event.objects.filter(bookings__user=self.request.user)