psachin
psachin

Reputation: 41

display foreignkey field in django template

I have models.py like below:

class Profile(models.Model):

    user = models.OneToOneField(User)

    def __unicode__(self):
        return "%s" % self.user

class Student(models.Model):

    user = models.ForeignKey(Profile)
    phone_num = models.CharField(max_length=15)

    def __unicode__(self):
        return "%s" % (self.user)

class Teacher(models.Model):

    user = models.ForeignKey(Profile)
    phone_num = models.CharField(max_length=15)

    def __unicode__(self):
        return "%s" % (self.user)

class Complaint(models.Model):

    user = models.ForeignKey(Student)
    complaint = models.TextField()
    teacher = models.ForeignKey(Teacher, null=True) 

    def __unicode__(self):
        return "%s : %s" % (self.complaint)

How can I display teacher's name which is eventually stored in class Profile What I get is a column teacher_id in _complaint table when I do

student_obj = Student.objects.get(name=user_profile_instance)

and then

compaint = student_obj.complaint_set.values()

in complaint.html

{{complaint.teacher_id}}

what I want is teacher name instead of id

Upvotes: 1

Views: 7069

Answers (2)

Anish Menon
Anish Menon

Reputation: 809

First of all Please Update your style of coding to make your App Optimised

Use

student_obj = Student.objects.select_related().get(name=user_profile_instance)

The Above one will Cache Datas . After that each time when u call Datas from fields it Wont HIT your database :) , Hence Your App will Fly

instead of

student_obj = Student.objects.get(name=user_profile_instance)

and i'm Agreeing with @Bibhas Answer

{{ complaint.teacher.user.user.first_name }}

Teacher's Profile is Inheriting Django's Auth Model User

That wise

user.user.first_name 

Upvotes: 2

Bibhas Debnath
Bibhas Debnath

Reputation: 14929

This should work -

{{ complaint.teacher.user.user.first_name }}

Upvotes: 7

Related Questions