Reputation: 33
lets say I have a dictionary called credit_facilities, where I map credit facility id to its verbal reprsentation.
credit_facilities = {1 : 'Yes',2:'No',3:'Not sure'}
I have model object where I retrieve values to be used as key for the dictionary. For instance lets say the model is named "customer" and it has attribute called "credit_facility". So, customer.credit_facility give either 1,2 or 3. I want to use this value as a key in dictionary. Meaning, is there an equivalent in django template language for the follwoing epression.
credit_facilities[customer.credit_facility]
Upvotes: 1
Views: 50
Reputation: 77942
Use a choices
argument for your credit_facility
field and the (automagic) get_credit_facility_display()
method to get the associated label:
class Customer(models.Model):
CREDIT_FACILITY_CHOICES = (
(1, "Yes"),
(2, "No"),
(3, "Not sure")
)
credit_facility = models.IntegerField(
"credit facility",
choices = CREDIT_FACILITY_CHOICES
)
then:
>>> c = Customer(1)
>>> c.get_credit_facility_display()
"Yes"
Full documentation here : https://docs.djangoproject.com/en/1.10/ref/models/fields/#choices
Upvotes: 2