简体   繁体   English

如何在Django DetailView中订购嵌套模型

[英]How to order nested model in django DetailView

I'm using Django 1.10 我正在使用Django 1.10

I'm learning Django by make Survey program 我正在通过Make Survey程序学习Django

I made three models, Survey include Questions, and Question include Choices 我制作了三个模型,“调查包括问题”和“问题包括选择”

Models.py Models.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)

I want to show my result page ordered by votes but now, I just show non-ordered result page. 我想按投票显示我的结果页,但现在,我只显示未排序的结果页。

I think I have to modify my views.py using queryset or extra context. 我想我必须使用queryset或其他上下文来修改views.py。 but I don't know how to use. 但我不知道该怎么用

Here is my views and template. 这是我的观点和模板。

views.py views.py

class SurveyResultsView(DetailView):
    model = Survey
    template_name = 'survey/results.html'

results.html results.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 %}

Thanks for read. 感谢您的阅读。

I can come up with three different ways that you can achieve this. 我可以提出三种不同的方法来实现这一目标。

Sort in Template 在模板中排序

The first, most obvious one is to sort the choice objects when you fetch them inside your template. 第一个,最明显的一个是,当您在模板中获取choice对象时,对它们进行排序。 You do this using the dictsort filter ( Docs ) that you apply like I show here below. 您可以使用像我在下面显示的那样应用的dictsort过滤器( Docs )来执行此操作。

{% for choice in question.choice_set.all|dictsort:"votes" %}
    <li>{{choice.choice_text}} -- {{choice.votes}} votes </li>
{% endfor %}

Note, there is also a dictsortreversed ( Docs ) filter that order the objects in reversed order. 请注意,还有一个dictsortreversedDocs )过滤器,可以按相反的顺序对对象进行排序。

Function on Model 型号功能

Another way of doing it is defining a function on the Question model that returns the entries in the sorted order that you wish for, and then instead of calling question.choice_set.all() in your template you would call the function instead. 另一种实现方法是在Question模型上定义一个函数,该函数以所需的排序顺序返回条目,然后代替调用模板中的question.choice_set.all()

Example: 例:

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')

Template: 模板:

{% for choice in question.choice_set_sorted %}
    <li>{{choice.choice_text}} -- {{choice.votes}} votes </li>
{% endfor %}

Setting the Meta class 设置元类

The third option is to set a default ordering on your Model. 第三个选项是在模型上设置默认顺序。 If you always want your Choice to be ordered by votes this could be a good idea. 如果您始终希望通过votesChoice您的Choice ,那么这可能是个好主意。

You do this by setting the Meta class in your model with the ordering property set to the field that you want to order by ( Docs ). 为此,您可以通过在模型中设置Meta类,并将ordering属性设置为您要ordering的字段( Docs )。

So the way you would implement this would be: 因此,您将实现以下方式:

class Choice(models.Model):
    #...
    class Meta:
        ordering = ['votes']

//// ////

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM