【问题标题】:django templatetags not return correct datadjango templatetags 不返回正确的数据
【发布时间】:2011-02-21 09:52:51
【问题描述】:

我已经构建了一个小型模板标签,用于查看我的数据库并根据记录的最受欢迎的奖杯进行计算。

模板标签如下:

@register.inclusion_tag('trophies/trophies.html')
def trophies():
    return { 'trophies': Trophies.objects.values("specie").annotate(Count("id")).order_by()}

trophies/trophies.html

{% for obj in trophies %}
    <li><a href="/trophy-room/browse/?specie={{ obj.specie }}">{{ obj.specie }}</a></li>
{% endfor %}

奖杯模型

class Trophies(models.Model):
    user = models.ForeignKey(User)
    specie = models.ForeignKey(Specie)

物种模型

class Specie(ImageModel):
    species = models.CharField(max_length=50, unique=True, verbose_name='Common Name')

运行 {{ obj.specie }} 返回 id,运行 {{ obj.specie.species }} 不返回任何内容。

为什么会这样?

【问题讨论】:

    标签: django django-views django-templates


    【解决方案1】:

    试试这个:

    @register.inclusion_tag('trophies/trophies.html')
    def trophies():
        return { 'trophies': Trophies.objects.values("specie", "specie__species").annotate(Count("id")).order_by()}
    

    在模板中:

    {{ obj.specie__species }}
    

    查看相关问题:Display Django values() on Foreign Key in template as object instead of its id

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-22
      • 1970-01-01
      • 2011-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-05
      • 2013-10-30
      相关资源
      最近更新 更多