tags:

views:

61

answers:

2

I have a django app with models as follows:

  • A Question model

  • An Answer model, with a ForeignKey back to the Question. (A question can have multiple answers.)

  • A Flag model, with a ForeignKey to the Answer. (An answer can be flagged as inappropriate.)

All of the above also have a user field, defining the user that created that object.

I'm trying to get a list of all Questions with answers from the current user which have been flagged. I tried this:

Question.objects.filter(answer__user=user).\
                 filter(answer__flag__isnull=False).distinct()

… but I believe that will return a list of Questions with answers from the current user and with answers which have been flagged, but will not necessarily guarantee that it is the user's answer that has been flagged.

Is there an easy way to do this? Basically, I want to make the answer part of the filter refer to the same answer on both of them.

Please let me know if something is unclear.

A: 

How about:

questions = [a.question for a in user.answer_set.filter(flag__isnull=True)]

Edit: this does not return a queryset, of course. And to prevent duplicate questions, maybe wrap the list comprehension in a set().

Dan Breen
I do, in fact, need it to be a queryset, because this may be passed off for further filtering later.
BJ Homer
+2  A: 

The query does exactly what you want, except that you should filter for questions where the flag is not null. Chained filters are anded together, so it will filter out all questions that have an answer from the particular user and then filter that set for answers that are flagged.

You may also put those two criteria in the same filter call:

Question.objects.filter(answer__user=user, answer__flag__isnull=False)
piquadrat
I'm not sure I understand. The first filter will give me a set of all Questions with at least one Answer from that user. Then, the second filter will return questions matching that criteria that have a flagged answer. But if Question Q1 has Answers A1 and A2 from Users U1 and U2, respectively, and A2 is flagged, won't this query return Q1 for both U1 and U2?And yes, you're absolutely right about isnull=False; I'll fix that.
BJ Homer
Aha. It turns out that if I put them both in the same filter call, then it will do what I want. (See http://docs.djangoproject.com/en/dev/topics/db/queries/#spanning-multi-valued-relationships for more info.)
BJ Homer