Django get display name choices

前端 未结 1 1872
时光取名叫无心
时光取名叫无心 2021-01-05 04:56

I\'m trying to find a solution to my problem.

models.py

class Article(models.Model):
    title = models.CharField(max_length=100)
    slug = models.S         


        
1条回答
  •  心在旅途
    2021-01-05 05:22

    Option #1:

    models.py

    CHOICES_QUALITY = (
        ('1', 'HD YB'),
        ('2', 'HD BJ'),
        ('3', 'HD POQD'),
        ('4', 'HD ANBC'),
    )
    
    class Article(models.Model):
        title = models.CharField(max_length=100)
        slug = models.SlugField()
        description = models.TextField()
    
        def archive_quality(self):
            quality = self.archive_set.order_by('-quality').distinct().values_list(
                'quality', flat=True)
            lists = []
            for q in quality:
                for choice in CHOICES_QUALITY:
                    if choice[0] == q:
                        lists.append({'quality': choice[1]})
            return lists
    
    class Archive(models.Model):
        article = models.ForeignKey(Article)
        quality = models.CharField(max_length=100, choices=CHOICES_QUALITY)
    

    template

    {% for article in articles %}
        {% for item in article.archive_quality %}
            {{ item.quality }},
        {% endfor %}
    {% endfor %}
    

    Option #2:

    archive_tag.py

    from django import template
    from app_name.models import CHOICES_QUALITY
    
    register = template.Library()
    
    @register.filter
    def quality(q):
        for choice in CHOICES_QUALITY:
            if choice[0] == q:
                return choice[1]
        return ''
    

    template

    {% load archive_tag %}
    
    {% for article in articles %}
        {% for item in article.archive_quality %}
            {{ item|quality }},
        {% endfor %}
    {% endfor %}
    

    0 讨论(0)
提交回复
热议问题