Django:如何返回item属性choice_set不为空的queryset?

时间:2017-07-03 11:06:28

标签: python django

FILE models.py

# Create your models here.
import datetime
from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('data published')
    def __str__(self):
        return 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 self.choice_text

FILE views.py

from django.views import generic
from .models import Question, Choice
from django.utils import timezone

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

    def get_queryset(self):
        """
        Excludes any questions that aren't published yet.
        """
        return Question.objects.filter(pub_date__lte=timezone.now())

使用python在数据库中创建问题:

from django.utils import timezone
from polls.models imoprt Question, Choice
q1 = Question.objects.create(pub_date=timezone.now(), question_text="1+1=?")
q1.choice_set.create(choice_text="A. 1")
q1.choice_set.create(choice_text="B. 2")
q2 = Question.objects.create(pub_date=timezone.now(), question_text="8+2=?")

在函数get_queryset中,如何返回该问题确实有选择的查询集?例如,Queryset INCLUDE q1(两个选项),但是EXCLUDE q2(没有选择)。

THX!

3 个答案:

答案 0 :(得分:1)

您可以通过排除IntentService来过滤问题,而无需选择。

你可以,

choice=None

您可以使用,def get_queryset(self): return Question.objects.filter(pub_date__lte=timezone.now()).exclude(choice=None) exclude(choice=None)

答案 1 :(得分:0)

您可以使用range(of:...)

进行过滤
:START
cls
set /A exe_count=%exe_count%+1
set /A mem_usage="wmic process where name='kill_tasks.bat' get WorkingSetSize | findstr /r "^[1-9][0-9]*"" 
title task kill -- execution count: %exe_count%, mem: %mem_usage%
<Other codes>
SLEEP 30
GOTO START

答案 2 :(得分:0)

from django.db.models import Count
Question.objects.exclude(choice__isnull=True).annotate(choice_count=Count('choice')).filter(choice_count=2)