使用 django templatetag 访问存储在字典中作为值的对象仅输出其字符串表示形式;不是原始对象
accessing objects stored in dictionary as values using django templatetag outputs only its string representation; not original object
在views.py
我正在构建一个字典,其中字符串 (A1、A2、A3....C10) 作为键,数据库对象作为值。
itemsByPosition = {}
for storage_instance in StorageInstance.objects.all():
itemsByPosition[storage_instance.cell] = storage_instance
在模板中,
我想显示对象的不同字段。
一个孤立的硬编码示例是(实际上我使用循环来打印整个字典):
{{ itemsByPosition|hash:'A2' }}
在templatetags.py
def hash(h,key):
if key in h:
return h[key]
else:
return None
register.filter(hash)
然而,模板标签'hash' returns模型的字符串表示(例如:"Stabi00052")不是整个对象。我希望能够在模板中访问该对象的各种属性。
如果键是除下划线以外不带空格或标点符号的字符串 (documentation)
,则无需自定义过滤器即可直接访问字典值
{{ itemsByPosition.A2.attribute }}
在views.py
我正在构建一个字典,其中字符串 (A1、A2、A3....C10) 作为键,数据库对象作为值。
itemsByPosition = {}
for storage_instance in StorageInstance.objects.all():
itemsByPosition[storage_instance.cell] = storage_instance
在模板中,
我想显示对象的不同字段。 一个孤立的硬编码示例是(实际上我使用循环来打印整个字典):
{{ itemsByPosition|hash:'A2' }}
在templatetags.py
def hash(h,key):
if key in h:
return h[key]
else:
return None
register.filter(hash)
然而,模板标签'hash' returns模型的字符串表示(例如:"Stabi00052")不是整个对象。我希望能够在模板中访问该对象的各种属性。
如果键是除下划线以外不带空格或标点符号的字符串 (documentation)
,则无需自定义过滤器即可直接访问字典值{{ itemsByPosition.A2.attribute }}