我正在使用 Django 1.10
我正在通过 make Survey 程序学习 Django
我做了三个模型,调查包括问题,问题包括选择
模型.py
from django.db import models
class Survey(models.Model):
title = models.CharField(max_length = 200)
description = models.TextField()
pub_date = models.DateTimeField('date published')
def __str__(self):
return self.title
class Question(models.Model):
survey = models.ForeignKey(Survey, on_delete=models.CASCADE)
question_text = models.CharField(max_length=200)
def __str__(self):
return "%s : %s" % (self.survey, self.question_text)
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __str__(self):
return "%s - %s" % (self.question, self.choice_text)
我想显示按投票排序的结果页面,但现在,我只显示非排序的结果页面。
我想我必须使用查询集或额外的上下文来修改我的 views.py。但是不知道怎么用。
这是我的观点和模板。
视图.py
class SurveyResultsView(DetailView):
model = Survey
template_name = 'survey/results.html'
结果.html
{% extends 'survey/base.html' %}
{% block content %}
<div class="survey-info-container">
<h1>Results of {{survey.title}}</h1>
<p>{{survey.description}}</p>
<p>{{survey.pub_date}}</p>
</div>
<div class="result-container">
{% for question in survey.question_set.all %}
<p>
<h3>{{question.question_text}}</h3>
<ul>
{% for choice in question.choice_set.all %}
<li>{{choice.choice_text}} -- {{choice.votes}} votes </li>
{% endfor %}
</ul>
</p>
{% endfor %}
</div>
{% endblock content %}
感谢阅读。
我可以想出三种不同的方法来实现这一目标。
第一个也是最明显的一个是choice
在您在模板中获取对象时对对象进行排序。您可以使用您应用的dictsort
过滤器 ( Docs )执行此操作,如下所示。
{% for choice in question.choice_set.all|dictsort:"votes" %}
<li>{{choice.choice_text}} -- {{choice.votes}} votes </li>
{% endfor %}
请注意,还有一个dictsortreversed
( Docs ) 过滤器以相反的顺序对对象进行排序。
另一种方法是在Question
模型上定义一个函数,该函数以您希望的排序顺序返回条目,然后不是question.choice_set.all()
在模板中调用,而是调用该函数。
例子:
class Question(models.Model):
#...
def choice_set_sorted(self):
# Can set .order_by('-votes') to reverse order
return self.choice_set.all().order_by('votes')
模板:
{% for choice in question.choice_set_sorted %}
<li>{{choice.choice_text}} -- {{choice.votes}} votes </li>
{% endfor %}
第三个选项是在您的模型上设置默认排序。如果您总是希望Choice
被订购,votes
这可能是一个好主意。
您可以通过将Meta
模型中的类ordering
设置为您想要排序的字段 ( Docs )的属性来完成此操作。
所以你实现这个的方式是:
class Choice(models.Model):
#...
class Meta:
ordering = ['votes']
////
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句