首页 > 解决方案 > 如何通过超模的属性过滤模型对象?

问题描述

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

模型.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

视图.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, )))

标签: djangodjango-modelsdjango-viewsdjango-tests

解决方案


您可以看到所有Choice实例都指向Question使用 django 的RelatedManager. 在这里阅读更多。

视图将是这样的:

class ListView(generic.ListView):
    model = Question

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

推荐阅读