Kieran
Kieran

Reputation: 7

Django reverse relations

I've managed to get my around Django for the most part but I'm still doing a pattern which I'm sure there exists a better way of doing but reading related questions I can't find a solution that works for me. It's a simple reverse relationship lookup which is then looped through in the template:

items_a = ItemA.objects.filter(foo='bar')
for item in items_a:
    items_a.items_b = ItemB.objects.filter(item_a=item_a)

I then use this so loop though in the template

Item A 1

Item A 2

Help!

Upvotes: 0

Views: 216

Answers (1)

catavaran
catavaran

Reputation: 45595

You don't need to populate the items_b property in a loop. Use the backward relationships instead:

items_a = ItemA.objects.filter(foo='bar')

And the in the template:

{% for item in items_a %}
    <h2>{{ item }}</h2>
    <ul>
    {% for item_b in item.itemb_set.all %}
        <li>{{ item_b }}</li>
    {% endfor %}
    </ul>
{% endfor %}

Upvotes: 2

Related Questions