python - How to use a ForeignKey field as filter in Django? -
i have 2 models:
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... .
i wrote view filtering albums specefic category, want them in home.html template:
#views.py def commercial(request): commercial_subjects = album.objects.filter(category__title__contains="commercial" ) return render(request, 'gallery/index.html', {'commercial_subjects': commercial_subjects}) and works fine commercial category. seems hardcoding if want write multiple views each category one. need view or filtering process shows categories , related album.subject automaticly. final result must this:
personal
- album 1
- album 2
commercial
- album 4
- album5
how can that?
its easy. first of give related_name foreign key:
class album(models.model): category = models.foreignkey(category, related_name='albums') from view pass categories:
def myview(request): categories = category.objects.all() return render(request, 'gallery/index.html', {'categories': categories}) then in template:
<ul> {% category in categories %} <li>{{ category.title }}</li> {% category.albums.all albums %} {% if albums %} <ul> {% album in albums %} <li>{{ album.subject }}</li> {% endfor %} <ul> {% endif %} {% endwith %} {% endfor %} </ul>
Comments
Post a Comment