Howto merge 2 Django QuerySets in one and make a SELECT DISTINCT

 picture · Jul 14, 2009 · Viewed 20.5k times · Source
models.py
class SinglePoint(models.Model):
    attributes = models.TextField(blank=True)
    name = models.CharField(max_length=100)
    geom = models.PointField() #Kartenposition
    objects = models.GeoManager()

class Connection(models.Model):
    name = models.CharField(max_length=100)
    #points = models.ManyToManyField(SinglePoint) #OLD
    p1 = models.ForeignKey(SinglePoint, related_name='p1_set') #NEW
    p2 = models.ForeignKey(SinglePoint, related_name='p2_set') #NEW
    obs = models.ManyToManyField(Observation, blank=True)
    conds = models.ManyToManyField(Condition, blank=True)
    objects = models.GeoManager()

class Meta:
    order_with_respect_to = 'p1'

In my view.py:

...
p1_points = SinglePoint.objects.filter(p1_set__vektordata__order__project__slug=slug)
p2_points = SinglePoint.objects.filter(p2_set__vektordata__order__project__slug=slug)
...

Before I switched to ForeignKey, it worked with:

points = SinglePoint.objects.filter(connection__vektordata__order__project__slug=slug)

How to 'join' these two QuerySets to one QuerySet and make a distinct()?

Thanks!

Answer

Krystian Cybulski picture Krystian Cybulski · Apr 9, 2013

It took me a while to find this

all_points = p1_points | p2_points