[Answered ]-Django how to generate a filtered queryset

1👍

You can simply iterate over the related objects in the template by using the default related name which is the model name in lowercase with _set appended. So asset_type.model_hardware_set.all() will give you all Model_hardware instances related to Asset_type and similarly for model_hardware.asset_set.all():

{% for model_hardware object.model_hardware_set.all %}
    {% for asset in model_hardware.asset_set.all %}
        {{ asset.name }}
    {% endfor %}
{% endfor %}

But this can become slow, since we run into the N + 1 problem that is for each model hardware we will be making queries to get it’s assets. We can use prefetch_related_objects on your model instance to prefetch all the related objects (in fewer queries) this and make it faster:

from django.db.models import prefetch_related_objects
from django.views.generic import DetailView


class YourDetailView(DetailView):
    model = Asset_type
    template_name = '<your_template_name>.html'
    
    def get_object(self, queryset=None):
        obj = super().get_object(queryset=queryset)
        prefetch_related_objects([obj], 'model_hardware__asset')
        return obj

Note: Class names in python should ideally be in PascalCase not Some_case (Don’t think there is any such convention as you make
here), hence ModelHardware instead of Model_hardware and
AssetType instead of Asset_type would be better names.

Leave a comment