9

我正在尝试找到解决我的问题的方法。

模型.py

class Article(models.Model):
    title = models.CharField(max_length=100)
    slug = models.SlugField()
    description = models.TextField()

def archive_quality(self):
    return self.archive_set.order_by('-quality').distinct().values_list('quality', flat=True)


class Archive(models.Model):
    CHOICES_QUALITY = (
        ('1', 'HD YB'),
        ('2', 'HD BJ'),
        ('3', 'HD POQD'),
        ('4', 'HD ANBC'),
    )
    article = models.ForeignKey(Article)
    quality = models.CharField(max_length=100, choices=CHOICES_QUALITY)

档案.html

{% for article in articles %}
    {{ article }}
    {% for quality in article.archive_quality %}
        {{ quality.get_quality_display }}#This is not working
    {% endfor %}
{% endfor %}

更新 功能 archive_quality 很重要,因为它可以防止模板对象中的重复出现。

Example:
article:
   My article one
Archive:
       quality: 1111222333 >> without the function
       quality: 123 >> with function
4

1 回答 1

11

选项1:

模型.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)

模板

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

选项#2:

归档标签.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 ''

模板

{% load archive_tag %}

{% for article in articles %}
    {% for item in article.archive_quality %}
        {{ item|quality }},
    {% endfor %}
{% endfor %}
于 2013-04-13T05:06:58.917 回答