QuerySets合并在一起

QuerySets合并在一起

本文介绍了如何将2个Django QuerySets合并在一起,并进行SELECT DISTINCT的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

model.py

  class SinglePoint(models.Model):
attributes = models.TextField(blank = True)
name = models.CharField(max_length = 100)
geom = models.PointField()#Kartenposition
objects = models.GeoManager()

类连接(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 =单点.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)

如何将这两个QuerySets加入到一个QuerySet中并创建一个distinct()?



解决方案

花了我一段时间找到这个

  all_points = p1_points | p2_points 


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!

解决方案

It took me a while to find this

all_points = p1_points | p2_points

这篇关于如何将2个Django QuerySets合并在一起,并进行SELECT DISTINCT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-04 20:43