[Answer]-How to use a ForeignKey field as filter in Django?

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>
πŸ‘€Aamir Rind

0πŸ‘

#views.py
def commercial(request):
    commercial_subjects = Album.objects.filter(category__title="commercial")
πŸ‘€Waheed

Leave a comment