Django: Filter a Queryset made of unions not working

As stated in django docs, only count(), order_by(), values(), values_list() and slicing of union queryset is allowed. You can't filter on union queryset.

That means, you have to apply filters on queries before applying union on them.

Also, you can achieve your goal without even using union():

Suite.objects.filter(role_set__users=self.get_user(), name="energia")

You may need to adjust field name in filter if you've used related_name or related_query_name in definition of suites M2M field in Role model.


I had the same issue and ended up using the union query as a subquery so that the filters could work:

yourModelUnionSubQuerySet = YourModelQS1.union(YourModelQS2)
yourModelUnionQuerySet = YourModel.objects.filter(id__in=yourModelUnionSubQuerySet.values('id'))

There is a simple solution. Just use

self.queryset = self.queryset | <querySet you want to append>

instead of

self.queryset = self.queryset.union(<QuerySet you want to append>)

Worked for me. I hope this is understandable. After this you will be able to use filter.

Tags:

Python

Django