假设我有一本名为 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/