[Answered ]-How to write out an object from a relationship in django

1👍

Yes, you work with:

{% for item in object_list %}
    {% for it in item.orderitem_set.all %}
        {{ it.product.title }}
    {% endfor %}
{% endfor %}

In the view, it is better to prefetch the items already, to prevent an N+1 problem with:

from django.db.models import Prefetch


class MyListView(ListView):
    model = Order
    queryset = Order.objects.prefetch_related(
        Prefetch('orderitem_set', OrderItem.objects.select_related('product'))
    )

while not necessary, this will result in two queries, whereas without this, it will require m×n+n+1 queries with N the number of Orders and m the number of OrderItems.

Leave a comment