I want to create a query that will lead to a list of users who have most of the events in which all of their dependent EventItems have rev1 and rev2 are not empty or null and active = True.
First, you want Event objects to always have this type of EventItem .
events = Event.objects.filter(active=True) events = events.exclude(eventitem__rev1__isnull=True) events = events.exclude(eventitem__rev1='') events = events.exclude(eventitem__rev2__isnull=True) events = events.exclude(eventitem__rev2='')
In addition, you did not indicate whether you want to deal with Event objects that do not have EventItem . You can filter them with:
events = events.exclude(eventitem__isnull=True)
Please note that events can contain many duplicates. You can add events.distinct() if you want, but you should only do this if you need it for human reading.
After that, you can now retrieve the User objects that you want:
users = User.objects.filter(event__in=events)
Note that on some * ahem * MySQL * ahem * database databases, you may find that the .filter(field__in=QuerySet) pattern .filter(field__in=QuerySet) very slow . In this case, the code should be:
users = User.objects.filter(event__in=list(events.values_list('pk', flat=True)))
Then you can order things by the number of Event objects attached:
from django.db.models import Count active_users = users.annotate(num_events=Count('event')).order_by('-num_events')
source share