如何在将对象传递给模板之前对其执行复杂排序?例如,以下是我的观点:
@login_required
def overview(request):
physicians = PhysicianGroup.objects.get(pk=physician_group).physicians
for physician in physicians.all():
physician.service_patients.order_by('bed__room__unit', 'bed__room__order', 'bed__order')
return render_to_response('hospitalists/overview.html', RequestContext(request, {'physicians': physicians,}))
模板中的医生对象的顺序不正确。为什么不?
另外,如何索引到模板内的列表中?例如,(这不起作用):
{% for note_type in note_types %}
<div><h3>{{ note_type }}</h3>
{% for notes in note_sets.index(parent.forloop.counter0) %}
#only want to display the notes of this note_type!
{% for note in notes %}
<p>{{ note }}</p>
{% endfor %}
{% endfor %}
</div>
{% endfor %}
谢谢你,皮特
您应该能够在视图中构造有序查询集并将其传递给模板:
然后,您的模板可以循环
patients
,该循环将包含有序的结果。这对你不管用吗?编辑:对于索引,只需使用点语法:模板中的
mylist.3
在python中变成mylist[3]
。有关详细信息,请参见http://docs.djangoproject.com/en/dev/ref/templates/api/#rendering-a-context。“我想在模板中执行此操作:”
不要。在它所属的视图函数中执行。
由于问题是不完整的,所以不可能猜测数据模型并提供精确的解决方案。
应该足够了。向模板提供
results
以进行呈现。它的顺序是正确的。如果排序不正确(可能是因为某些模型的微妙之处),那么您总是有这样的选择。
向模板提供
patient_list
以进行呈现。它的顺序是正确的。“如何索引到模板内的列表中”
我不知道你想做什么,但大多数时候,答案是“不要”。在“查看”功能中执行此操作。
模板只是遍历简单的列表来填充简单的HTML模板。
如果对模板来说太复杂,那么它就是。保持模板简单——它只是演示。在view函数中进行处理
正如其他人所指出的,这两个问题最好都在模板之外解决——要么在模型中,要么在视图中。一种策略是将helper方法添加到相关类中。
获取医生患者的排序列表:
在模板中,使用
physician.sorted_patients
,而不是physician.patients
。对于“display the notes of this note嫒type”,听起来您可能需要note嫒type类的
notes
方法。根据你的描述,我不确定这是否是一个模型类,但原理是一样的:然后模板:
相关问题 更多 >
编程相关推荐