简体   繁体   English

模板中的Django对象查找

[英]Django object lookups in templates

I am going through the Django project tutorial, and in this section it says: 我正在阅读Django项目教程,在节中它说:

The template system uses dot-lookup syntax to access variable attributes. 模板系统使用点查找语法来访问变量属性。 In the example of {{ question.question_text }}, first Django does a dictionary lookup on the object question. 在{{question.question_text}}的示例中,首先Django对对象问题进行字典查找。 Failing that, it tries an attribute lookup – which works, in this case. 如果失败,它将尝试属性查找-在这种情况下可以工作。 If attribute lookup had failed, it would've tried a list-index lookup. 如果属性查找失败,它将尝试进行列表索引查找。

Does this mean that the Django question is a dictionary object, and in the first instance, looks for question_text as the key, and if found, returns the value? 这是否意味着Django question是一个字典对象,并且在第一个实例中,将question_text作为键,如果找到,则返回值? Beyond this, I can't visualise what the two fall-back options are doing. 除此之外,我无法想象这两个后备选项的作用。

Does this mean that the Django question is a dictionary object, and in the first instance, looks for question_text as the key, and if found, returns the value? 这是否意味着Django question是一个字典对象,并且在第一个实例中,将question_text作为键,如果找到,则返回值? Beyond this, I can't visualise what the two fall-back options are doing. 除此之外,我无法想象这两个后备选项的作用。

question doesn't have to be a literal dict for the first option to work. question并不一定是文字dict对于第一种选择工作。 It needs to be dictionary-like. 它必须像字典一样。 That is, question['question_text'] works in Python. 也就是说, question['question_text']在Python中有效。

The first fallback refers to regular Python dot notation. 第一个后备广告是指常规的Python点表示法。 For example, if either of these works in Python: 例如,如果以下任何一种在Python中都有效:

question.question_text  # or
question.question_text()

then question.question_text will work in the template returning the Python value. 然后question.question_text将在返回Python值的模板中工作。 Note that parentheses are omitted in both cases. 注意,两种情况都省略括号。

The final fallback is numeric indexing. 最后的后备方法是数字索引。 For example, if question is a list and this works in Python: 例如,如果question是一个列表并且在Python中有效:

question[0]

then question.0 will work in the template, returning the value of question[0] . 然后question.0 question[0]将在模板中工作,返回question[0]的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM