本文介绍了Django 模板列表的第一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我将字典传递给我的 Django 模板,
I pass a dictionary to my Django Template,
字典&模板是这样的——
Dictionary & Template is like this -
lists[listid] = {'name': l.listname, 'docs': l.userdocs.order_by('-id')}
{% for k, v in lists.items %}
<ul><li>Count: {{ v.docs.count }}, First: {{ v.docs|first }}</li></ul>
{% endfor %}
现在 docs
是 userdocs
类型的列表.即是一个实例.所以 first
过滤器返回我这个实例.从中我需要提取它的 id
.我该怎么做?
Now docs
is a list of userdocs
type. i.e. is an instance. So first
filter returns me this instance. From this I need to extract it's id
. How do I do that?
我试过了{{ v.docs|first }}.id
和其他各种徒劳的试验.
I tried{{ v.docs|first }}.id
and various other futile trials.
推荐答案
您可以将 {% with %}
模板标签用于此类事情.
You can use the {% with %}
templatetag for this sort of thing.
{% with v.docs|first as first_doc %}{{ first_doc.id }}{% endwith %}
这篇关于Django 模板列表的第一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!