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

jth*_*son 9 python django

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

user-name
phone-number
Run Code Online (Sandbox Code Playgroud)

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

{{ user-name }}
Run Code Online (Sandbox Code Playgroud)

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

Eva*_*ley 8

如果您不想重新构建对象,则自定义模板标记可能是此处的唯一方法.要使用任意字符串键访问字典,此问题的答案提供了一个很好的示例.

对于懒惰:

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, '')
Run Code Online (Sandbox Code Playgroud)

您使用的是这样的:

{% dictKeyLookup your_dict_passed_into_context "phone-number" %}
Run Code Online (Sandbox Code Playgroud)

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

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)
Run Code Online (Sandbox Code Playgroud)

您将使用哪个:

{% attributeLookup your_object_passed_into_context "phone-number" %}
Run Code Online (Sandbox Code Playgroud)

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


Mat*_*hen 5

不幸的是,我认为你可能不走运。从文档

变量名称必须由任意字母 (AZ)、任意数字 (0-9)、下划线或点组成。