[Answered ]-Chain-Model Getting all objects for template

1👍

The error message suggests that there is no attribute named 'proje' on the sirket object. This is because you have defined the foreign key relation on the Proje model, not on the Sirket model.

So use the following view:

def firma(request):
    sirket = Sirket.objects.all().prefetch_related('proje_set__santiye_set__personel_set').order_by('id')
    return render(request, "firma.html", {"sirket": sirket})

Here, we are prefetching the related objects from Proje to Personel using the "__" syntax to traverse through the foreign key relations.

Then use in the template as:

<div class="container">
    <div class="row">
        {% for s in sirket %}
            <div class="card mb-3">
                <div class="row">
                    <div class="col-md-3">
                    </div>
                    <div class="col-md-9">
                        <div class="card-body">
                            <p class="card-text"><b>{{s.isim}}:</b></p>
                            {% for p in s.proje_set.all %}
                                <p class="card-text"><b>{{p.ad}}:</b></p>
                                {% for san in p.santiye_set.all %}
                                    <p class="card-text"><b>{{san.isim}}:</b></p>
                                    {% for per in san.personel_set.all %}
                                        <li>{{per.ad}}</li>
                                    {% endfor %}
                                {% endfor %}
                            {% endfor %}
                        </div>
                    </div>
                </div>
            </div>
        {% endfor %}
    </div>
</div>

0👍

This is a bit complex to debug without mirroring the same project on my machine. But here is a possible solution you can try.

In your view, you can use a prefetch-related method to fetch all related objects to the Sirket model.

sirket = Sirket.objects.all().prefetch_related(
    'proje_set__santiye_set__personel_set'
).order_by('id')

This should allow you to access the related Personel objects from the Sirket object in your template.

{% for sirket in sirket %}
    <div class="card mb-3">
        <div class="row">
            <div class="col-md-3">
            </div>
            <div class="col-md-9">
                <div class="card-body">
                    <p class="card-text"><b>Çalışan Personeller:</b></p>
                    <p>
                        {% for proje in sirket.proje_set.all %}
                            {% for santiye in proje.santiye_set.all %}
                                {% for personel in santiye.personel_set.all %}
                                    <li>{{personel.ad}}</li>
                                {% endfor %}
                            {% endfor %}
                        {% endfor %}
                    </p>
                </div>
            </div>
        </div>
    </div>
{% endfor %}

Leave a comment