访问django模板引擎中的字典

时间:2016-12-30 12:05:26

标签: 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]

1 个答案:

答案 0 :(得分:2)

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