python - 在 django 模板引擎中访问字典

标签 python django dictionary

假设我有一本名为 Credit_facilities 的字典,我在其中将信用设施 ID 映射到其口头表示。

credit_facilities = {1 : 'Yes',2:'No',3:'Not sure'}

我有模型对象,在其中检索要用作字典键的值。例如,假设模型名为“customer”,它具有名为“credit_facility”的属性。因此,customer.credit_facility 给出 1,2 或 3。我想使用这个值作为字典中的键。意思是,django 模板语言中是否有与以下表达式等效的内容。

credit_facilities[customer.credit_facility]

最佳答案

使用 choices 参数作为您的 credit_facility 字段和(自动)get_credit_facility_display() 方法来获取关联的标签:

class Customer(models.Model):
    CREDIT_FACILITY_CHOICES = (
      (1, "Yes"),
      (2, "No"),
      (3, "Not sure")
      )
    credit_facility = models.IntegerField(
       "credit facility", 
       choices = CREDIT_FACILITY_CHOICES
       )

然后:

>>> c = Customer(1)
>>> c.get_credit_facility_display()
"Yes"

完整文档在这里:https://docs.djangoproject.com/en/1.10/ref/models/fields/#choices

关于python - 在 django 模板引擎中访问字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41395999/

相关文章:

django - 在 Wagtail 中创建可重用字段集的方法?

python - Django ORM 查询延迟字段,它不应该

javascript - Django 中的 Jquery 帖子

java - 在 Java 8 中使用 Lambda 遍历一个 Map of Maps?

python - 如何在 Matlab 的 virtualenv 中执行 Python 代码

python - 优化 ReadTheDocs 项目的构建时间

python - lxml.etree.XPathEvalError : Invalid expression

python - django 'int' 对象没有属性 'save'

python - python 模块的数据描述符

C++ unordered_map 其中键也是 unordered_map