Sometimes you would like to show the description of a choice instead of its code in a Django template. One way to achieve that is to define a property in the model and referencing it in a template as below:
{{ object.status_desc }}
=== models.py ===
from django.db.models import IntegerField, CharField, Model
class Invoice(Model):
STATUS_TYPE = (
('A', 'Active'),
('I', 'Inactive'),
)
invoice_no = IntegerField()
status = CharField(max_length=1, choices=STATUS_TYPE, default='A')
@property
def status_desc(self):
return dict(self.STATUS_TYPE)[self.status]
EDITED 2015-07-13 Turn out there is a django function for this purpose: Model.get_FOO_display()
No comments:
Post a Comment