HOWTO合并2个Django的查询集于一体,使一个SELECT DISTINCT(Howto me

2019-06-25 21:27发布

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'

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

之前,我切换到外键,它的工作有:

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

如何“加入”这两个查询集到一个查询集,并作出不同的()?

谢谢!

Answer 1:

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

all_points = p1_points | p2_points


Answer 2:

我不熟悉GeoDjango内置,但查询集组合成一个查询集通过Q-对象和布尔运算符是可能的。 见http://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects

例:

Q(p1_points) | Q(p2_points)

我不能帮你进一步,因为我真的不知道你要完成的任务。



Answer 3:

我认为, Q的查询可以实现你所需要的是这样的:

points = SinglePoint.objects.filter(
    Q(p1_set__vektordata__order__project__slug=slug) |
    Q(p2_set__vektordata__order__project__slug=slug)
).distinct()


Answer 4:

p1_points.union(p2_points)

见文档



文章来源: Howto merge 2 Django QuerySets in one and make a SELECT DISTINCT