[Django]-How to combine two querysets when defining choices in a ModelMultipleChoiceField?

5đź‘Ť

âś…

You can combine querysets by using the | and & operators.

from functools import reduce
from operator import and_, or_

querysets = [q1, q2, q3, ...]  # List of querysets you want to combine.

# Objects that are present in *at least one* of the queries
combined_or_querysets = reduce(or_, querysets[1:], querysets[0])

# Objects that are present in *all* of the queries
combined_and_querysets = reduce(and_, querysets[1:], querysets[0])

From Django 1.11+ you can also use the union and intersection methods.

0đź‘Ť

I’ve found a “solution” to this problem. If I structure the query like so, I can get everything I need in one swoop without having to combine querysets after the fact:

desired_value = Trope.objects.filter(genre_relation__in=preferred_genres).distinct()

I still do not know how to combine multiple querysets into one without losing the inherent “queryset-ness” that seems to be necessary for the form to render properly. However, for my specific use case, restructuring the query as noted renders the issue moot.

👤souldeux

Leave a comment