[Django]-Django reverse lookup of foreign keys

173👍

You can use events = venue.event_set to go the other way.

Note that venue.event_set is a manager object, like Event.objects, so you can call .all, .filter, .exclude and similar on it to get a queryset.

See the Django documentation

👤Ric

10👍

To those who have “‘RelatedManager’ object is not iterable”

Add all to retrieve the elements from the manager.

{% for area in world_areas.all %}

https://stackoverflow.com/a/16909142/2491526
(cannot add this in comment to the first answer)

👤Apex

6👍

Go the other way round. Use Event model.

def detail(request, venue_id):
    venue = Event.objects.filter(venue__id=venue_id)
    return render(request, 'venue-detail.html', {'venue': venue})

PS: I have never used get_object_or_404(). Modify code accordingly.

👤rjv

1👍

You can use venue.event_set.all() to get all the events that are happening at a certain venue as shown below:

def detail(request, venue_id):
    venue = get_object_or_404(Venue, pk=venue_id)
    events = venue.event_set.all() # Here
    return render(request, 'venue-detail.html', {'events': events})

Leave a comment