determining if a one-to-many relation exists

3,443 views
Skip to first unread message

Jim N

unread,
Apr 12, 2010, 11:50:53 AM4/12/10
to Django users
Hi Djangoists,

I have a model "question" which has a one-to-many relationship with
"answer".

class Question(models.Model):
text = models.TextField()

class Answer(models.Model):
text = models.TextField()
question = models.ForeignKey(Question)

I can't figure out how to construct a filter that will give me

- just questions where there isn't an answer
- just questions where there is an answer

Is this really easy and I'm just not seeing it?

Thanks,
Jim

Jim N

unread,
Apr 12, 2010, 12:20:03 PM4/12/10
to Django users
Just to clarify, I'm trying to filter questions that have an answer,
but I don't know the particular answer. I just want to determine
whether or not an answer object exists, with the foreign key of this
question.

I could do

Answer.objects.filter(question = my_question)

but I am filtering questions on a number of parameters, such as text
of the question.

Thanks,
Jim

Nick Serra

unread,
Apr 12, 2010, 1:21:38 PM4/12/10
to Django users
You could query like this:

Question.objects.filter(answer__isnull=False)

This would give you a set of questions where an answer exists. Setting
it to True would give you a set where answers don't exist.

Jim N

unread,
Apr 12, 2010, 1:32:58 PM4/12/10
to Django users
Yes! That's it! Thank you.

Nick Serra

unread,
Apr 12, 2010, 1:47:59 PM4/12/10
to Django users
Welcome! You might just want to incorporate the answer into the
question model, and then do a boolean field for is_answered for quick
reference. The thought of multiple answers for one question seems odd,
and use of one-to-one fields isn't recommended, so i'd just keep it in
one model l)
Reply all
Reply to author
Forward
0 new messages