django - 如何通过超模的属性过滤模型对象?
问题描述
为了开始使用 Django,我做了 Django 本身提供的介绍。tests
在它的第 5 部分中,您为views
and编写了一些内容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, )))
解决方案
您可以看到所有Choice
实例都指向Question
使用 django 的RelatedManager
. 在这里阅读更多。
视图将是这样的:
class ListView(generic.ListView):
model = Question
def get_queryset(self):
return Question.objects.filter(choice__isnull = False)
推荐阅读
- javascript - Heroku 推送失败并出现构建错误
- sql - 无法在连接条件中应用 case 语句
- python - 使用 Pandas Python 格式化具有给定限制的数据表
- github - GitHub - 工作:什么是:使用操作/结帐
- linux - NPM 不会自动为我设置 cmdlet?
- flutter - 单击时如何更改按钮的图标?
- spring - NestJS 提供者是否需要是无状态的?
- c# - C# Xamarin 使用 TCP 套接字从流字节数组中接收和显示图像
- php - php exec() 与 get 或 post
- vue.js - 如何解决 Nuxt.js 找不到模块“@vue/composition-api”错误?