Search code examples
python-3.xdjangodjango-rest-frameworkoperatorsdjango-queryset

Django Rest : AssertionError: Cannot combine a unique query with a non-unique query


I'm trying to get a queryset with unique instances of a model project. when I try to combine multiple querysets with & operator like:

projects = (q1_projects & q2_projects & q3_projects)

I get this error:

AssertionError: Cannot combine a unique query with a non-unique query.


Solution

  • As quoted by ruddra

    You can use union() to combine different querysets like this:

    q1_projects = Model.objects.filter(...)
    q2_projects = Model.objects.filter(...)
    q3_projects = Model.objects.filter(...)
    
    projects = q1_projects.union(q2_projects, q3_projects)
    

    That will give same result as:

    projects = q1_projects & q2_projects & q3_projects
    

    Note: The UNION operator selects only distinct values by default. To allow duplicate values, use the all=True argument.

    But if you want to order_by on the ForeignKey, you have to use select()