[Answered ]-Complex Django query

2đź‘Ť

âś…

This should work:

Group.objects.exclude(~Q(person__position="worker"))

Edit:

The above wasn’t correct so here’s my second try:

Group.objects.filter(
    Q(person__position="worker") 
    & ~Q(person__position__gt="worker")
    & ~Q(person__position__lt="worker")
)

I am unsure if this can be used with all databases. It works with my PGSQL installation.

👤XORcist

0đź‘Ť

Look into annotation: http://docs.djangoproject.com/en/dev/topics/db/aggregation/

I can’t recall the exact syntax, but you should be able to annotate each Group with the number of Persons with position=”worker” as well as the total number of Persons, then filter it to only the Groups where those two counts are equal.

👤baddox

Leave a comment