Django reverse lookup of foreign keys


Question

I have a venue, this venue has many events happening there. My models look like this:

class Event(models.Model):
    title = models.CharField(max_length=200)
    date_published = models.DateTimeField('published date',default=datetime.now, blank=True)
    date_start = models.DateTimeField('start date')
    date_end = models.DateTimeField('end date')
    def __unicode__(self):
        return self.title
    description = models.TextField()
    price = models.IntegerField(null=True, blank=True)
    venue = models.ForeignKey(Venue)

class Venue(models.Model):
    title = models.CharField(max_length=200)
    date_published = models.DateTimeField('published date',default=datetime.now, blank=True)
    venue_latitude = models.CharField(max_length=200)
    venue_longitude = models.CharField(max_length=200)
    venue_address = models.CharField(max_length=200)
    venue_city = models.CharField(max_length=200)
    venue_state = models.CharField(max_length=200)
    venue_country = models.CharField(max_length=200)
    description = models.TextField()
    def __unicode__(self):
        return u'%s' % (self.title)

I'd like to display all the events that are happening at a certain venue. How can I do that? My current view looks like:

def detail(request, venue_id):
    venue = get_object_or_404(Venue, pk=venue_id)
    return render(request, 'venue-detail.html', {'venue': venue})
1
54
3/9/2013 3:43:54 AM

Accepted Answer

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

See the Django documentation

86
3/9/2013 4:41:09 AM

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)


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon