LeLouch
LeLouch

Reputation: 611

displaying data in django template using detail view

i'm having a problem displaying data on DetailView Template , basically wanna display all the data of one project areas and tasks my models looks like that

##models    
class Project(models.Model):
        name = models.CharField(max_length=100)
        ...


    class Area(models.Model):
        name = models.CharField(max_length=100)
        project = models.ForeignKey(Project ,on_delete=models.CASCADE,  related_name='areas' )

    class Task(models.Model):
        ....
        area = models.ForeignKey(Area ,on_delete=models.CASCADE,  related_name='tasks' )

#view 
class ProjectDetailView(DetailView):
    model = Project
    template_name = 'project-detail.html'

this finaly worked in template

{% for area in object.areas.all %}
    {{area}}<br />
    {% for t in area.tasks.all %}
     {{ t }}<br />
     {% endfor %}
     <hr/>
{% endfor %}

Upvotes: 0

Views: 158

Answers (1)

Ngoc Pham
Ngoc Pham

Reputation: 1458

you can try prefetch_related and modify Detail like this:

#view 
class ProjectDetailView(DetailView):
    model = Project
    template_name = 'project-detail.html'
    def get_queryset(self):
        return Project.objects.all().prefetch_related('areas__tasks')

and try show data task in template

Upvotes: 1

Related Questions