0

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?

setchock
  • 151
  • 1
  • 2
  • 9

1 Answers1

4

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

  • That is a cleaner approach, thanks. I added ".distinct()" at the end to only get the events a single time. But is that efficient in terms of queries? can you tell me how many queries this would produce? – setchock Aug 18 '16 at 10:10
  • Ah yes, may need a distinct there. This is a single query, you can see it with `print Event.objects.filter(bookings__user=self.request.user).query`. – Björn Kristinsson Aug 18 '16 at 10:16