繁体   English   中英

在Django模板引擎中访问字典

[英]Accessing dictionary in django template engine

可以说我有一本名为credit_facilities的字典,在其中我将信贷工具ID映射到其口头表达。

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

我有模型对象,可以在其中检索要用作字典键的值。 例如,假设模型被命名为“客户”,并且其属性为“ credit_facility”。 因此,customer.credit_facility给出1,2或3。我想将此值用作字典中的键。 意思是,以下模板在django模板语言中是否有等效项。

credit_facilities[customer.credit_facility]

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

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

暂无
暂无

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

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