How to write a Django view to obtain CharFields of multiple Django models that can only be accessed through relations
-
21-08-2019 - |
Question
Please see the following Django models: -
class Student(models.Model):
reference_num = models.CharField(max_length=50, unique=True)
name = models.CharField(max_length=50)
birthdate = models.DateField(null=True, blank=True)
is_active = models.BooleanField(db_index=True)
class Examination(models.Model):
short_name = models.CharField(max_length=20, unique=True)
name = models.CharField(max_length=50, unique=True)
is_active = models.BooleanField(db_index=True)
class Subject(models.Model):
short_name = models.CharField(max_length=20, unique=True)
name = models.CharField(max_length=50, unique=True)
is_active = models.BooleanField(db_index=True)
class EducationalQualification(models.Model):
student = models.ForeignKey(Student)
examination = models.ForeignKey(Examination)
subject = models.ForeignKey(Subject, null=True, blank=True)
institution = models.CharField(max_length=50)
from_date = models.DateField(null=True, blank=True)
to_date = models.DateField()
marks = models.DecimalField(max_digits=5, decimal_places=2)
I need to display the last model "EducationalQualification) for a given Student in a grid (a Student can have multiple EducationalQualifications).
The grid has columns for "Name of student", "Short Name of examination", "Short Name of Subject", "EducationalQualification.institution", "EducationalQualification.from_date", "EducationalQualification.to_date", and "EducationalQualification.marks" .
I have been unable to come up with a Django view to get this data (given a Student.pk)
Could someone please help me with a few ideas?
Regards.
Solution
You just need to fetch all EducationalQualification
objects for certain student with all their relation objects:
def view_qualifications(request, student_id):
qs = EducationalQualification.objects.filter(student__pk=student_id).\
select_related("student", "examination", "subject")
# ...
And then in template just iterate throught it:
{% for q in qs %}
<tr>
<td>{{q.student.name}}</td>
<td>{{q.examination.short_name}}</td>
<td>{{q.subject.short_name}}</td>
<td>{{q.institution}}</td>
<td>{{q.from_date}}</td>
<td>{{q.to_date}}</td>
<td>{{q.marks}}</td>
</tr>
{% endfor %}
OTHER TIPS
Create a database view and a model which specifies managed = False
in it's Meta class.