0

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 just wrote a view for filtering albums by specefic category, also I want them all 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 it works fine for just commercial category. It seems just like hardcoding if I want to write multiple views for each category like this one. What I need is a view or filtering process which shows all categories and their related album.subject automaticly. So the final result must be like this:

Personal

  • ALBUM 1
  • ALBUM 2

Commercial

  • ALBUM 4
  • ALBUM5

How can I do that?

2 Answers 2

1

Its easy. First of all give a related_name to the foreign key:

class Album(models.Model): category = models.ForeignKey(Category, related_name='albums') 

From view pass all categories:

def myView(request): categories = Category.objects.all() return render(request, 'gallery/index.html', {'categories': categories}) 

Then in template:

<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> 
Sign up to request clarification or add additional context in comments.

Comments

0
#views.py def commercial(request): commercial_subjects = Album.objects.filter(category__title="commercial") 

1 Comment

This is just what I said. I want sth to list all categories and related albums, not just list albums related to commercial category.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.