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

时间:2011-11-24 04:59:11

标签: python django

我们有一个基于自定义数据库的系统,其中许多属性被命名为包含连字符,即:

user-name
phone-number

无法在模板中访问这些属性,如下所示:

{{ user-name }}

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

3 个答案:

答案 0 :(得分:8)

如果您不想重新构建对象,自定义模板标记可能是唯一的方法。对于使用任意字符串键访问字典,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" %}

您甚至可以为子属性提供某种字符串分隔符(如“__”),但我会将其留给作业: - )

答案 1 :(得分:4)

不幸的是,我认为你可能会失败。来自docs

  

变量名必须包含任何字母(A-Z),任何数字(0-9),a   下划线或点。

答案 2 :(得分:1)

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

这似乎是OrderedDict实现的副作用。请注意,键值对实际上是作为集合传入的。我敢打赌,OrderedDict的实现不会使用集合中传递的“key”作为真正的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