我对Django queryset分组有问题。我需要获取由point
捕捉网格ST_SnapToGrid摸索的点的queryset,查询应如下所示:
SELECT
ST_AsGeoJSON(
ST_SnapToGrid("events_place"."point", 1),
8
) AS "point_geo",
MAX("events_place"."adress") AS "adress"
FROM
"events_place"
GROUP BY
point_geo
并且代码无效:
models.py
class Place(models.Model):
kode= models.BigIntegerField(blank=True, null=True)
adress = models.CharField(max_length=250, blank=True, null=True)
lat = models.FloatField(blank=True, null=True)
lng = models.FloatField(blank=True, null=True)
point = models.PointField(blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return str(self.id) + " "+str(self.adress ) + " ("+str(self.lat) + ", " + str(self.lat) + ")"
class Meta:
ordering = ('created_at',)
def save(self, *args, **kwargs):
super(Place, self).save(*args, **kwargs) # Call the "real" save() method.
views.py
class PlaceSTGViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Place.objects.all()
serializer_class = PlaceSTGSerializer
def get_queryset(self):
queryset = Place.objects\
.annotate(point_geo=AsGeoJSON(SnapToGrid('point', 1)), adress=Max('adress'))\
.values('lng', 'point_geo')
return queryset
结果查询无效:
SELECT
"events_place"."lng",
ST_AsGeoJSON(
ST_SnapToGrid("events_place"."point", 1),
8
) AS "point_geo"
FROM
"events_place"
GROUP BY
"events_place"."id",
ST_AsGeoJSON(
ST_SnapToGrid("events_place"."point", 1),
8
)
ORDER BY
"runis_events_place"."created_at" ASC
问题是它按语句包含了"events_place"."id"
。您能告诉我如何摆脱此id
吗?
在此问题中找到答案:Django annotate and values(): extra field in 'group by' causes unexpected results,该问题与order_by有关