如何通过模型对象的超模型属性过滤模型对象?

时间:2019-12-10 14:46:20

标签: django django-models django-views django-tests

要开始使用Django,我做了Django本身提供的介绍。在第5部分中,您为testsviews写了一些models。之后,他们会为您提供更多tests的想法。这是我的问题开始的地方。他们建议您仅显示Questions且数字Choices大于0。我不知道该怎么做。我当前的代码可以在https://github.com/byTreneib/django.git上找到。 Django教程位于https://docs.djangoproject.com/en/3.0/intro/tutorial05/

models.py

from django.db import models
from django.utils import timezone
import datetime


class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    def __str__(self):
        return self.question_text

    def was_published_recently(self):
        return timezone.now() >= self.pub_date >= timezone.now() - datetime.timedelta(days=1)


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 self.choice_text

views.py

from django.shortcuts import render
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.template import loader
from django.shortcuts import render, get_object_or_404
from django.db.models import F
from .models import Question, Choice
from django.urls import reverse
from django.views import generic
from django.utils import timezone


class IndexView(generic.ListView):
    template_name = 'polls/index.html'
    context_object_name = 'latest_question_list'

    def get_queryset(self):
        return Question.objects.filter(pub_date__lte=timezone.now()).filter().order_by('-pub_date')[:5]


class DetailView(generic.DetailView):
    model = Question
    template_name = 'polls/detail.html'

    def get_queryset(self):
        return Question.objects.filter(pub_date__lte=timezone.now())


class ResultsView(generic.DetailView):
    model = Question
    template_name = 'polls/results.html'

    def get_queryset(self):
        return Question.objects.filter(pub_date__lte=timezone.now())


def vote(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    try:
        selected_choice = question.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        return render(request, 'polls/detail.html', {'question': question, 'error_message': "No choice selected!"})
    else:
        selected_choice.votes = F('votes') + 1
        selected_choice.save()
        return HttpResponseRedirect(reverse('polls:results', args=(question.id, )))

1 个答案:

答案 0 :(得分:1)

您可以使用Django的Choice查看指向Question的所有RelatedManager实例。了解更多here

视图将如下所示:

class ListView(generic.ListView):
    model = Question

    def get_queryset(self):
        return Question.objects.filter(choice__isnull = False)