Django filter with two constraints on related model
- by BJ Homer
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=True).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.