我想列出所有在電影模式是類型ForeignKey的相關對象說comedy
類型列表中的所有影片對象相關comedy
Django的select_related FK模型
# models.py
class Genre(models.Model):
name = models.CharField(max_length=80, unique=True)
slug = models.SlugField(unique=True)
def __unicode__(self):
return self.name
def get_absolute_url(self):
return reverse("genres:list", kwargs={"slug": self.slug})
class Movie(models.Model):
title = models.CharField(max_length=80)
genre = models.ForeignKey(Genre)
# views.py
def genre_list(request, slug):
instance = get_object_or_404(Genre, slug=slug)
movies = Movie.objects.select_related('genre').all()
context = {
"objects_list": movies,
}
return render(request, 'genres/genres_list.html', context)
模板視圖genres/genres_list.html
{% for obj in objects_list %}
<div class="box">
<b>{{ obj.title }}</b>
</div>
{% endfor %}
什麼都沒有變成我做錯了什麼?
'「object_list」'不應該是'movies',而不是像你的代碼中的'shows'? – doru