sheshkovsky
sheshkovsky

Reputation: 1340

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 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?

Upvotes: 0

Views: 75

Answers (2)

Waheed
Waheed

Reputation: 665

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

Upvotes: 0

Aamir Rind
Aamir Rind

Reputation: 39659

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>

Upvotes: 1

Related Questions