【发布时间】:2012-01-05 08:19:42
【问题描述】:
我们有一个建立在自定义数据库上的系统,其中许多属性的命名都包含连字符,即:
user-name
phone-number
这些属性无法在模板中访问,如下所示:
{{ user-name }}
Django 为此抛出异常。我想避免必须将所有键(和子表键)转换为使用下划线来解决这个问题。有没有更简单的方法?
【问题讨论】:
我们有一个建立在自定义数据库上的系统,其中许多属性的命名都包含连字符,即:
user-name
phone-number
这些属性无法在模板中访问,如下所示:
{{ user-name }}
Django 为此抛出异常。我想避免必须将所有键(和子表键)转换为使用下划线来解决这个问题。有没有更简单的方法?
【问题讨论】:
如果您不想重构对象,自定义模板标签可能是唯一的方法。对于使用任意字符串键访问字典,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" %}
您甚至可以为子属性想出某种字符串分隔符(例如 '__'),但我会把它留作家庭作业 :-)
【讨论】:
不幸的是,我认为你可能不走运。来自docs:
变量名称必须由任意字母 (A-Z)、任意数字 (0-9)、 下划线或点。
【讨论】:
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
【讨论】: