views:

180

answers:

1

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.

+3  A: 

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 %}
Alex Koshelev
Works perfectly! I was thinking this wouldn't work because I had null=True for the subject ForeignKey. But it works exactly like it should.You could even say RTFM I guess :) Thanks.
chefsmart
If you a a student object you can reference it the other way too.student.educationqualification_set.all() will get you the same thing.
dalore