如何从Django模板中访问包含连字符的字典键?

2024-04-20 00:08:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我们有一个建立在自定义数据库上的系统,其中许多属性的名称都包含连字符,即:

user-name
phone-number

在模板中无法按以下方式访问这些属性:

{{ user-name }}

Django对此抛出了一个异常。我想避免将所有键(和子表键)转换为使用下划线来解决这个问题。有更简单的方法吗?


Tags: django方法name名称模板数据库number属性
3条回答

OrderedDict字典类型支持破折号: https://docs.python.org/2/library/collections.html#ordereddict-objects

这似乎是实施OrderedDict的副作用。注意下面的键值对实际上是以集合的形式传入的。我敢打赌,OrderedDict的实现不会使用集合中传递的“密钥”作为真正的dict密钥,从而绕过这个问题。

因为这是OrderedDict实现的副作用,所以可能不是您想要依赖的东西。但它起作用了。

from collections import OrderedDict

my_dict = OrderedDict([
    ('has-dash', 'has dash value'), 
    ('no dash', 'no dash value') 
])

print( 'has-dash: ' + my_dict['has-dash'] )
print( 'no dash: ' + my_dict['no dash'] )

结果:

has-dash: has dash value
no dash: no dash value

如果不想重新构造对象,自定义模板标记可能是唯一的方法。对于使用任意字符串键访问字典,this question的答案提供了一个很好的示例。

对于懒惰的人:

from django import template
register = template.Library()

@register.simple_tag
def dictKeyLookup(the_dict, key):
   # Try to fetch from the dict, and if it's not found return an empty string.
   return the_dict.get(key, '')

你这么用的:

{% dictKeyLookup your_dict_passed_into_context "phone-number" %}

如果要使用任意字符串名称访问对象的属性,可以使用以下命令:

from django import template
register = template.Library()

@register.simple_tag
def attributeLookup(the_object, attribute_name):
   # Try to fetch from the object, and if it's not found return None.
   return getattr(the_object, attribute_name, None)

你想用的是:

{% attributeLookup your_object_passed_into_context "phone-number" %}

你甚至可以为子属性设计一些字符串分隔符(比如'\uuu'),但我把它留给家庭作业:-)

不幸的是,我想你可能走运了。从docs

Variable names must consist of any letter (A-Z), any digit (0-9), an underscore or a dot.

相关问题 更多 >