在django项目中显示来自views.py的表

时间:2017-09-23 22:42:35

标签: python html mysql django

<table class="table">
     <thead>
     <tr>
          <th>School</th>
          <th>Strength</th>
          <th>Average</th>
     </tr>
     </thead>
     <tbody>
     {% for school in cluster.school_set.all %}
          <tr>
               <td><a href="{% url 'data:school_detail' state.id region.id cluster.id school.id %}">{{ school.school_name }}</a></td>
               <td>{{ school.strength }}</td>
               <td>school average</td>
          </tr>
      {% endfor %}
      </tbody>
</table>

这是我模板中的表格,以表格形式显示群集(城镇/城市)中所有学校的详细信息,其中列为1)学校名称2)学校实力3)学校平均分数来自一定数量的考试。 我可以很容易地获得第1列学校名称和数据的数据。 2)学校实力,因为他们只是班级学校的领域。问题在于列平均值。为了得到平均值,我需要有一些代码行,我不能直接在模板中做。问题是我不知道如何在views.py中做到这一点。计算我需要school.id但是从url我只得到cluster.id 在这些情况下,如果您不能简单地从views.py获取数据而不从模板中提供值,该怎么办?

set = Average.objects.filter(school=school.id):
obj = set.latest('average_date')
avg = obj.average_value

这些是我获得特定学校平均水平所需的代码行。

class School(models.Model):
    state = models.ForeignKey(State, on_delete=models.CASCADE)
    region = ChainedForeignKey(Region, chained_field="state",chained_model_field="state", show_all=False, auto_choose=True, sort=False, on_delete=models.CASCADE)
    cluster = ChainedForeignKey(Cluster, chained_field="region",chained_model_field="region", show_all=False, auto_choose=True, sort=False, on_delete=models.CASCADE)
    school_name = models.CharField(max_length=250)
    facilitator = models.CharField(max_length=250)
    f_number = models.IntegerField()
    f_email = models.EmailField()
    school_logo = models.FileField(default='')
    strength = models.IntegerField()

    def __str__(self):
        return self.school_name


class Avergae(models.Model):
    state = models.ForeignKey(State, on_delete=models.CASCADE)
    region = ChainedForeignKey(Region, chained_field="state",chained_model_field="state", show_all=False, auto_choose=True, sort=False, on_delete=models.CASCADE)
    cluster = ChainedForeignKey(Cluster, chained_field="region",chained_model_field="region", show_all=False, auto_choose=True, sort=False, on_delete=models.CASCADE)
    school = ChainedForeignKey(School, chained_field="cluster",chained_model_field="cluster", show_all=False, auto_choose=True, sort=False, on_delete=models.CASCADE)
    average_date = models.DateField()
    average_value = models.DecimalField(max_digits=4, decimal_places=2)
    average_attendance = models.IntegerField()
    average_note = models.CharField(max_length=250)

    def __str__(self):
        return '{}: {}'.format(self.average_date, self.average_value)

这些是我的学校和平均模型

1 个答案:

答案 0 :(得分:3)

School模型中,您可以编写方法get_average

class School(models.Model):
    # other fields
    def get_average(self):
        return self.avergae_set.latest('average_date').average_value

然后在模板中你可以这样做:

{{ school.get_average }}

注意:您的平均模型名称拼写是错误的,您有Avergae而应该是Average