23
模型.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'

在我看来.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)
...

在我切换到 ForeignKey 之前,它适用于:

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

如何将这两个查询集“加入”到一个查询集并创建一个 distinct()?

谢谢!

4

4 回答 4

72

我花了一段时间才找到这个

all_points = p1_points | p2_points
于 2013-04-09T07:37:25.040 回答
8

我不熟悉 geodjango,但是可以通过 Q-Object 和布尔运算符将 QuerySet 组合成一个 QuerySet。请参阅http://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects

例子:

Q(p1_points) | Q(p2_points)

我无法进一步帮助您,因为我不确定您要完成什么。

于 2009-07-14T14:54:20.080 回答
6

我认为Q 查询可以像这样实现您所需要的:

points = SinglePoint.objects.filter(
    Q(p1_set__vektordata__order__project__slug=slug) |
    Q(p2_set__vektordata__order__project__slug=slug)
).distinct()
于 2013-06-21T12:56:10.700 回答
3

p1_points.union(p2_points)

查看文档

于 2019-04-12T13:01:31.440 回答