Django - сортировка результатов ("выбор") по количеству голосов
Не знаю, как вывести на страницу результат каждого "выбора" в порядке убывания в зависимости от количества полученных "голосов". Пожалуйста, помогите мне с решением. Ниже приведена моя настройка. Спасибо!
models.py
class Question(models.Model):
question_text = models.CharField(max_length=200, verbose_name='Intrebare')
pub_date = models.DateTimeField('publicat la:')
def __str__(self):
return self.question_text
class Meta:
verbose_name = 'Intrebari sondaj'
verbose_name_plural = 'Intrebari sondaj'
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200, verbose_name='')
votes = models.IntegerField(default=0)
def __str__(self):
return self.choice_text
class Meta:
verbose_name = 'Variante raspuns'
verbose_name_plural = 'Variante raspuns'
views.py
# preluare si afisare intrebari din sondaj
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
context = {'latest_question_list': latest_question_list}
return render(request, 'sondaj/index.html', context)
# afisare optiuni aferente fiecarei intrebari din sondaj si intrebare in sine
def detail(request, question_id):
try:
question = Question.objects.get(pk=question_id)
except Question.DoesNotExist:
raise Http404("Nu exista sondaje publicate")
return render(request, 'sondaj/detail.html', {'question' : question})
# preluare si afisare rezultate la nivelul fiecarei intrebari sondaj
@login_required(login_url='/')
def results(request, question_id):
question = get_object_or_404(Question, pk=question_id)
comments = question.comments
return render(request, 'sondaj/results.html', {'question': question, 'comments' : comments})
# listare optiuni de ales pentru fiecare intrebare din sondaj
def vote(request, question_id):
#print (request.POST['choice'])
question = get_object_or_404(Question, pk=question_id)
try:
selected_choice = question.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
# reafisare intrebare sondaj daca nu s-a ales nimic
return render(request, 'sondaj/detail.html', {
'question' : question,
'error_message' : "Trebuie sa selectezi una din variantele existente",
})
else:
selected_choice.votes += 1
selected_choice.save()
# redirectionare dupa vor; acum arata rezultatele dar trebuie sa creez mai bine o pagina de "multumesc pentru vot, adaud in url etc"
return HttpResponseRedirect(reverse('sondaj:results', args=(question.id,)))
results.html
{% for choice in question.choice_set.all %}
<div class="row g-0 mb-2 p-2">
<div class="col-auto">
<div class="sw-3 d-inline-block d-flex justify-content-start align-items-center h-100">
<div class="sh-3">
<i data-acorn-icon="check-circle" data-acorn-size="20" class="text-dark"></i>
</div>
</div>
</div>
<div class="col">
<div class=" d-flex flex-column pt-0 pb-0 ps-3 pe-4 h-100 justify-content-center">
<div class="d-flex flex-column">
<div class="text-dark mt-n1 lh-1-25"> {{ choice.choice_text}} </div>
</div>
</div>
</div>
<div class="col-auto">
<div class="d-inline-block d-flex justify-content-end align-items-center h-100">
<div class="text-muted ms-2 mt-n1 lh-1-25"><h4><span class="badge bg-muted ">{{ choice.votes }} </span> <span style="font-size:x-small;">voturi</span> </h4> </div>
</div>
</div>
</div>
<hr>
{% endfor %}
Я пытаюсь на странице resuls.html поставить что-то вроде этого, но не работает ({% for choice in question.choice_set.all.order_by(choice.votes %}
)