[Django]-How to merge 2 Django QuerySets in one and make a SELECT DISTINCT

74👍

It took me a while to find this

all_points = p1_points | p2_points

9👍

I am not familiar with geodjango, but combining QuerySets into one QuerySet is possible via the Q-Object and Boolean Operators. See http://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects

Example:

Q(p1_points) | Q(p2_points)

I can’t help you further, because I am not really sure what you are trying to accomplish.

7👍

I think Q queries can achieve what you need like this:

points = SinglePoint.objects.filter(
    Q(name=name) |
    Q(name=name)
).distinct()
👤JoshB

3👍

p1_points.union(p2_points)

See Docs

1👍

You can use "|"(bitwise or) to combine the querysets of the same model and distinct() and values_list() as shown below:

all_points = (p1_points | p2_points).distinct().values_list('name')

And, you can use |= to add the queryset of the same model as shown below:

all_points = p1_points 
all_points |= p2_points
all_points = all_points.distinct().values_list('name')

Leave a comment