Reputation: 6958
I have a model, Respondent
, related to another model Questionnaire
via a ManyToMany
field named finished
.
I have a set of four Questionnaire
objects and would like to retrieve all Respondent
objects that have a finished
relationship with all four.
I would also like to retrieve the inverse: Any Respondent
object which doesn't have a finished
relationship with all four selected Questionnaire
objects.
I've been looking through the docs, and haven't found something that works for me. I am able to get all of the Respondent
objects that match at least one of the Questionnaire
objects with Respondent.objects.filter(finished__in=questionnaire_queryset)
but that's as far as I've gotten.
Upvotes: 2
Views: 29
Reputation: 476659
You could count the number of finished
objects that are in the questionnaire_queryset
, like:
from django.db.models import Count
Respondent.objects.filter(
finished__in=questionnaire_queryset
).annotate(
nfinish=Count('finished')
).filter(
nfinish=len(questionnaire_queryset)
)
We make an assumption here that questionnaire_queryset
does not contain any duplicates.
Upvotes: 2