【问题标题】:Django View / Template how to know the max value from a modelDjango View / Template如何知道模型的最大值
【发布时间】:2014-02-27 20:39:56
【问题描述】:

我正在处理包含两个模型的 https://docs.djangoproject.com 教程项目。

投票:

class Poll(models.Model):
    question = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')
    def was_published_recently(self):
        now = timezone.now()
        return now - datetime.timedelta(days=1) <= self.pub_date < now
    was_published_recently.admin_order_field = 'pub_date'
    was_published_recently.boolean = True
    was_published_recently.short_description = 'Published recently?'
    def __unicode__(self):
        return self.question

和选择:

class Choice(models.Model):
    poll = models.ForeignKey(Poll)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)
    def __unicode__(self):
        return self.choice_text

有一个显示投票问题的详细信息视图,以及该问题的选项,并允许用户投票。还有一个结果视图,它再次显示问题,以及每个选项的当前投票数。

我已正确显示所有内容,但我正在尝试添加本教程未涵盖的功能,我不确定如何去做。我想让它在结果页面上获得最多票数的选择获得某种特殊格式,以将其表示为当前领导者。

现在在模板中,我只有一个 for 循环,用于输出每个选项,并且它的值以它们存储的顺序排列。

{% extends "polls/base.html" %}

{% block content %}
<h1>{{ poll.question }}</h1>

<ul>
{% for choice in poll.choice_set.all %}
    <li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li>
{% endfor %}
</ul>

<a href="{% url 'polls:detail' poll.id %}">Vote again?</a>
{% endblock %}

当我在 for 循环中时,我有点想弄清楚如何知道我是否在投票最多的选择中,以便我可以有某种条件来更改格式。

我只需要在正确的方向上稍微推动一下。模板本身是否有某种方法可以让我知道哪个选项的投票最多?还是我需要在视图中弄清楚并将其传递给模板?如果两者都可能,那么其​​中一个会被认为是首选吗?

【问题讨论】:

    标签: python django django-models django-templates django-views


    【解决方案1】:

    如果我理解正确,你可以写custom assignment template tag,然后在if...else中使用。

    {% get_max_votes poll.choice_set.all as leader %}
    {% for choice in poll.choice_set.all %}
        {% ifequal choice leader %}
        {% endif %}
    {% endfor %}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多