Howto merge 2 Django QuerySets in one and make a S

2019-02-08 00:04发布

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!

3条回答
劫难
2楼-- · 2019-02-08 00:35

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.

查看更多
Explosion°爆炸
3楼-- · 2019-02-08 00:54

It took me a while to find this

all_points = p1_points | p2_points
查看更多
贼婆χ
4楼-- · 2019-02-08 00:54

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

points = SinglePoint.objects.filter(
    Q(p1_set__vektordata__order__project__slug=slug) |
    Q(p2_set__vektordata__order__project__slug=slug)
).distinct()
查看更多
登录 后发表回答