[Answered ]-Django prefetch_related over 3 models (one "relationship Model"

1👍

Don’t use .values(..) or .values_list(..), it will erode the model layer.

work with:

from django.db.models import Prefetch

qs = VULDB.objects.prefetch_related(
    Prefetch('clientvuldb_set', ClientVULDB.objects.select_related('VID'))
)

in the template, render with:

<ul>
{% for item in qs %}
  <li>{{ qs.Hostname }}
  <ul>
  {% for subitem in item.clientvuldb_set.all %}
    <li>{{ subitem.VID.Title }}</li>
  {% endfor %}
  </ul>
{% endfor %}
</ul>

Note: normally the name of the fields in a Django model are written in snake_case, not PascalCase, so it should be: title instead of Title.


Note: Models normally have no Db suffix. A model is not a table, it is stored in a relational database as a table, but even then it has extra logic like validators, managers, etc.

Leave a comment