我试图按照学校平均分数的降序显示群集(城市或城镇)中的学校表。
<table class="table">
<thead>
<tr>
<th>School</th>
<th>Strength</th>
<th>Average</th>
</tr>
</thead>
<tbody>
{% for school in school_order %}
<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.get_average }}</td>
</tr>
{% endfor %}
</tbody>
</table>
这是我试图在我的模板中显示的表格
school_order = cluster.school_set.all().order_by('-get_average')
这就是我在view.py
中尝试获取school_order的方法get_average不是模型学校的字段,但它是我在模型中使用的方法。
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 get_average(self):
return self.avergae_set.latest('average_date').average_value
这是我的学校模式。
我收到的错误无法解析关键字&#39; get_average&#39;进入田野。
请帮忙!
答案 0 :(得分:0)
你不能将Django ORM的orderby用于非模型字段。您可以将查询集转换为列表并在python中进行排序。
school_order = list(cluster.school_set.all())
.sort(key=lambda x: x.get_average, reverse=True)
您可以选择其他选项或注释。
参考:https://docs.djangoproject.com/en/1.11/ref/models/querysets/#annotate