@MrKMV34
Превозмогая трудности

Как сделать выборку объектов на которые не ссылаются внешние ключи в Django 1.8?

Здравствуйте.
Есть модель:
import datetime

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


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

    def __unicode__(self):
        return self.question_text

    def was_published_recently(self):
        now = timezone.now()
        return now - datetime.timedelta(days=1) <= self.pub_date <= now
        
    was_published_recently.admin_order_field = 'pub_date'
    was_published_recently.boolean = True
    was_published_recently.short_description = 'Published recently?'

class Choice(models.Model):
    poll = models.ForeignKey(Question)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField()

    def __unicode__(self):
        return self.choice_text

Модель описывает вопрос-ответы, за одним вопросом может быть закреплено от 0 до N ответов.
Есть views.py:
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.views import generic
from django.utils import timezone

from .models import Choice, Question


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

    def get_queryset(self):
        """
        Return the last five published questions (not including those set to be
        published in the future).
        """
        return Question.objects.filter(
            pub_date__lte=timezone.now()
        ).order_by('-pub_date')[:5]


Суть вопроса: Какие параметры указать в Question.objects.filter() чтобы получать только те вопросы, на которые есть варианты ответов?
  • Вопрос задан
  • 541 просмотр
Пригласить эксперта
Ответы на вопрос 1
@deliro
from django.db.models import Count
Question.objects.annotate(count=Count('choice')).filter(count__gt=0)
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы