0

请参阅以下 Django 模型:-

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)

我需要在网格中显示给定学生的最后一个模型“EducationalQualification”(一个学生可以有多个 EducationalQualifications)。

网格包含“学生姓名”、“考试简称”、“学科简称”、“EducationalQualification.institution”、“EducationalQualification.from_date”、“EducationalQualification.to_date”和“EducationalQualification.marks”列。

我一直无法想出一个 Django 视图来获取这些数据(给定一个 Student.pk)

有人可以帮我一些想法吗?

问候。

4

2 回答 2

3

您只需要获取EducationalQualification某个学生的所有对象及其所有关系对象:

def view_qualifications(request, student_id):
    qs = EducationalQualification.objects.filter(student__pk=student_id).\
                           select_related("student", "examination", "subject")
    # ...

然后在模板中遍历它:

{% 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 %}
于 2009-03-24T07:58:23.397 回答
0

managed = False创建一个数据库视图和一个在其 Meta 类中指定的模型。

于 2012-07-20T16:16:09.617 回答