Home > OS >  Django display attribute of intermediary entity through parent entity
Django display attribute of intermediary entity through parent entity

Time:03-17

I am trying to reference an attribute from the Material_Requisition_Items intermediary entity through the Material_Requisition.reqItems ManytoManyField and have it displayed on HTML; however, it references the Item parent entity instead.

Is there a way to reference attributes from the intermediary entity through the parent in Django HTML?

models.py

[Intermediary Entity]

class Material_Requisition_Items(models.Model):
    reqID = models.ForeignKey("Material_Requisition", on_delete=models.CASCADE)
    itemID = models.ForeignKey('item.Item', on_delete=models.CASCADE)
    ...
    itemQuantity = models.PositiveIntegerField(default=0, null=True)

[Parent Entity]

class Material_Requisition(models.Model):
    ...
    reqItems = models.ManyToManyField(
            Item,
            through="Material_Requisition_Items",
            through_fields=('reqID', 'itemID'),
            related_name="mat_req_items"
            )

requisition_detail.html

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

views.py

class RequisitionDetailView(LoginRequiredMixin, generic.DetailView):
    model = Material_Requisition
    template_name = "requisition/requisition_detail.html"
    context_object_name = "requisition"

CodePudding user response:

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.

  • Related