外键的 Django 反向查找

我有一个场地,这个场地有很多活动在那里进行。我的模特们看起来是这样的:

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)

我想展示一下在某个地点发生的所有事件。我该怎么做?我现在的看法是:

def detail(request, venue_id):
venue = get_object_or_404(Venue, pk=venue_id)
return render(request, 'venue-detail.html', {'venue': venue})
138662 次浏览

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.

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

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)