M
M
MrKMV342015-09-12 20:12:04
Django
MrKMV34, 2015-09-12 20:12:04

How to select objects not referenced by foreign keys in Django 1.8?

Hello.
There is a model:

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

The model describes the question-answers, one question can be assigned from 0 to N answers.
There is 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]

The essence of the question: What parameters to specify in Question.objects.filter() to receive only those questions for which there are options for answers?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Kitaev, 2015-09-12
@deliro

from django.db.models import Count
Question.objects.annotate(count=Count('choice')).filter(count__gt=0)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question