假设我有一个名为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]
答案 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