Django templates: verbose version of a choice

前端 未结 8 1156
野性不改
野性不改 2020-11-30 18:16

I have a model:

from django.db import models

CHOICES = (
    (\'s\', \'Glorious spam\'),
    (\'e\', \'Fabulous eggs\'),
)

class MealOrder(models.Model):
          


        
8条回答
  •  余生分开走
    2020-11-30 18:19

    Add to your models.py one simple function:

    def get_display(key, list):
        d = dict(list)
        if key in d:
            return d[key]
        return None
    

    Now, you can get verbose value of choice fields like that:

    class MealOrder(models.Model):
        meal = models.CharField(max_length=8, choices=CHOICES)
    
        def meal_verbose(self):
            return get_display(self.meal, CHOICES)    
    

    Upd.: I'm not sure, is that solution “pythonic” and “django-way” enough or not, but it works. :)

提交回复
热议问题