[Answered ]-Django display attribute of intermediary entity through parent entity

1👍

Yes, you can access the relation with the material_requisition_items_set manager instead:

{% for item in object.material_requisition_items_set.all %}
    <td>{{ item.itemID.itemName }}</td>
    <td>{{ item.itemQuantity }}</td>
{% endfor %}

You can boost efficiencly by prefetching and immediately selecting the related itemID with a Prefetch object [Django-doc]:

from django.db.models import Prefetch

class RequisitionDetailView(LoginRequiredMixin, generic.DetailView):
    model = Material_Requisition
    queryset = Material_Requisition.objects.prefetch_related(
        Prefetch('material_requisition_items_set', Material_Requisition_Items.objects.select_related('itemID'))
    )
    template_name = 'requisition/requisition_detail.html'
    context_object_name = 'requisition'

Note: normally a Django models, just like all classes in Python are given a name in PascalCase, not snake_case, so it should be: MaterialRequisitionItems instead of Material_Requisition_Items.


Note: Normally one does not add a suffix ID to a ForeignKey field, since Django
will automatically add a "twin" field with an _id suffix. Therefore it should
be item, instead of itemID.

Leave a comment