【问题标题】:Accessing dictionary in django template engine在 django 模板引擎中访问字典
【发布时间】:2016-12-30 12:05:25
【问题描述】:

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

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

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

credit_facilities[customer.credit_facility]

【问题讨论】:

  • 写一个自定义模板过滤器:见那个帖子:stackoverflow.com/questions/8000022/…
  • 您应该将此设置为您的字段的选择属性,然后您就可以在模板中执行customer.get_credit_facility_display

标签: python django dictionary


【解决方案1】:

为您的credit_facility 字段使用choices 参数和(自动)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

【讨论】:

    猜你喜欢
    • 2021-10-17
    • 2014-02-08
    • 1970-01-01
    • 2021-04-10
    • 2013-11-13
    • 2013-12-03
    相关资源
    最近更新 更多