I have two models both with a M2M field pointing to the same third model:
class Moo(models.Model):
...
class Foo(models.Model):
moos = models.ManyToManyField(Moo, blank=True)
class Bar(models.Model):
moos = models.ManyToManyField(Moo)
I need to find all ‘Foo’ objects that either have no ‘manytomany’ objects selected, or at least one manytomany objects that match an individual ‘Bar’ object.
So my data might look like this:
foo1.moos__all = 'boo', 'yah'
foo2.moos__all = <none>
foo3.moos__all = 'suck'
bar1.moos__all = 'boo'
Then doing this search would produce:
bar1.find_matches()
>>> foo1, foo2
The data model used to have to include at least one item match, so was easy as:
Foo.objects.filter(manytomany__in=bar1.moos.all())
Now the model has changed, and Foo.moos can be blank. So in short, I need to do this:
Foo.objects.filter(
Q(moos__in=bar1.moos.all()) | Q(moos__count=0)
)
Sadly __count is not an option 🙁
Any bright ideas?
Does the following not work?