我有2个型号:
class Category(models.Model):
title = models.CharField(max_length=250)
### other fields
class Album(models.Model):
category = models.ForeignKey(Category)
subject = models.CharField(max_length=200)
### other fields...
我刚刚写了一个用于通过specefic类别过滤相册的视图,我也希望它们都在home.html模板中:
#views.py
def commercial(request):
commercial_subjects = Album.objects.filter(category__title__contains="commercial" )
return render(request, 'gallery/index.html', {'commercial_subjects': commercial_subjects})
它适用于商业类别。如果我想为每个类别编写多个视图,就好像硬编码一样。我需要的是一个视图或过滤过程,它自动显示所有类别及其相关的album.subject。所以最终的结果必须是这样的:
个人
- ALBUM 1
- ALBUM 2
商业
- ALBUM 4
- ALBUM5
我该怎么做?
答案 0 :(得分:1)
很容易。首先给外键related_name:
class Album(models.Model):
category = models.ForeignKey(Category, related_name='albums')
从视图传递所有类别:
def myView(request):
categories = Category.objects.all()
return render(request, 'gallery/index.html', {'categories': categories})
然后在模板中:
<ul>
{% for category in categories %}
<li>{{ category.title }}</li>
{% with category.albums.all as albums %}
{% if albums %}
<ul>
{% for album in albums %}
<li>{{ album.subject }}</li>
{% endfor %}
<ul>
{% endif %}
{% endwith %}
{% endfor %}
</ul>
答案 1 :(得分:0)
#views.py
def commercial(request):
commercial_subjects = Album.objects.filter(category__title="commercial")