如何将2个Django查询集合并为一个并进行SELECT DISTINCT

xcitsw88  于 2023-01-27  发布在  Go
关注(0)|答案(5)|浏览(142)
www.example.commodels.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(name=name)
p2_points = SinglePoint.objects.filter(name=name)
...

在我切换到外键之前,它可以:

points = SinglePoint.objects.filter(name=name)

如何将这两个QuerySet "连接"为一个QuerySet并创建一个distinct()?
谢谢!

nlejzf6q

nlejzf6q1#

我花了点时间才找到这个

all_points = p1_points | p2_points
x6h2sr28

x6h2sr282#

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

Q(p1_points) | Q(p2_points)

我不能再帮你了,因为我真的不知道你想达到什么目的。

zrfyljdw

zrfyljdw3#

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

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

vddsk6oq4#

p1_points.union(p2_points)
参见文档

whhtz7ly

whhtz7ly5#

您可以使用“|“(按位或)合并相同模型的查询集,以及distinct()和values_list(),如下所示:

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

并且,可以使用|=添加相同模型的查询集,如下所示:

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

相关问题