Reputation: 21
Okay, so I have a model for locations and menu options and a many to many relationship between them.
What I would like to do is display menu options that are not already attached to the location. So I did this..
options = Options.objects.exclude(location=location_pk)
However, this results in menu options that don't currently have any location relationships not appearing on the list.
What I would like to do is the union of these two:
Options.objects.filter(location=None)
Options.objects.exclude(location=location_pk)
I tried...
options = options.filter(Q(location=None) | ~Q(location=location_pk))
...but when an option has multiple locations then the ~Q(location=location_pk)
will just match the other location.
Can anyone help?
I'm sure this must be possible but part of me thinks it might not be or that the solution may need to be needlessly complex.
Thanks.
Upvotes: 1
Views: 791
Reputation: 21
Okay, so I found a solution.
This seems to do the job...
Option.objects.exclude(~Q(location=None) & Q(location=location_pk))
Will need to have a look closer at the sql output for the queries to see exactly what's going on.
Thankful that it didn't take longer than I thought to figure out and isn't complex. phew
Upvotes: 1