1👍
Okay, I hope this helps someone else:
We need to put Q | Q in Q to achieve the results
user = User.objects.get(id=1)
qs = Notification.objects.all().annotate(
is_in_manytomany=ExpressionWrapper(
Q(Q(manytomany=user)| Q(manytomany=None)),
output_field=BooleanField()
)
)
for item in qs:
print(item.is_in_manytomany)
Explanation: we did not need to do manytomany__in=[user]
, because its a ManyToMany
field; manytomany=user
is enough, since some objects have manytomany=None
(because in my case the manytomany=ManyToManyField(User, blank=True)
, we need to add the second Q(manytomany=None)
. Also to reverse the boolean we can add ~
to any Q
expression.
Source:stackexchange.com