Vikrant Agrahari
Vikrant Agrahari

Reputation: 163

How to display Foreign Key related models fields values in HTML with Django?

I passed a list from Views.py to HTML in a dictionary value. I loop through the fields. There's one column which is Foreign key to another model. Only that model realted information is not displaying in HTML. How to solve this? The following is the code. The Foreign key column "Course" is not showing but others. Screenshot attached here

Views.py

def Student_Main(request):
    objs= Students.objects.values().all()
    template_name = 'genius/students.html'
    context = {'head_title': 'Little Genius Students', 'students':objs}
    return render(request, template_name, context)

HTML

<table class="table table-hover">
                <thead class="thead-dark">
                    <tr>
                    <th scope="col">#</th>
                    <th scope="col">Name</th>
                    <th scope="col">DOB</th>
                    <th scope="col">Age</th>
                    <th scope="col">Gender</th>
                    <th scope="col">Grade</th>
                    <th scope="col">School</th>
                    <th scope="col">Course</th>
                    <th scope="col">Address</th>

                    </tr>
                </thead>
                <tbody>
                    {% for i in students %}
                    <tr>
                    <th scope="row">{{i.id}}</th>
                    <td><a href=''>{{i.name}}</a></td>
                    <td>{{i.dob}}</td>
                    <td>{{i.age}}</td>
                    <td>{{i.gender}}</td>
                    <td>{{i.grade}}</td>
                    <td>{{i.attending_school}}</td>
                    <td>{{i.course.class_name}}</td>
                    <td>{{i.address}}</td>
                    </tr>
                    {% endfor %}
                </tbody>
</table>

Upvotes: 1

Views: 437

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476557

Please do not use .values() [Django-doc], it should be used very scarcely, for example if you want to make a GROUP BY on a set of values. Just omitting the .values() will return you Model objects, that make use of lazy loading to follow ForeignKeys:

def Student_Main(request):
    # no .values()
    objs = Students.objects.all()
    template_name = 'genius/students.html'
    context = {'head_title': 'Little Genius Students', 'students':objs}
    return render(request, template_name, context)

You can make use of .select_related(..) [Django-doc] to prevent the N+1 problem, and select the related course in the query:

def Student_Main(request):
    objs = Students.objects.select_related('course')
    template_name = 'genius/students.html'
    context = {'head_title': 'Little Genius Students', 'students':objs}
    return render(request, template_name, context)

Upvotes: 1

Related Questions