[Fixed]-How to access other model's attribute in one model via Foreign key in django?

1👍

Since grade is going to be that of the Class instance of Student, I would suggest removing the grade class variable from Student and instead adding a property to the class Student. Like this.

class Student(models.Model):
    name = models.CharField(u'姓名', max_length=64)
    sex = models.CharField(u'性别', max_length=64)
    id_num = models.CharField(u'身份证号', max_length=64)
    student_num = models.CharField(u'学号', max_length=64)
    class_id = models.ForeignKey('Class', verbose_name=u'班级', related_name='class_id')

    def __unicode__(self):
        return self.name

    @property
    def grade_name(self):
        return self.class.grade.name

And to get the grade of a Student instance, it would be

student = Student.object.all()[0]
grade = student.grade_name

0👍

#get first student in table 
s = Student.object.all()[0]
# get Grade access through Class model
print s.class_id.grade
👤mtt2p

Leave a comment