Query of a subquery in Django

﹥>﹥吖頭↗ 提交于 2019-12-07 17:12:01

问题


I'm trying to do a query from another query, but Django said: 'Caught DatabaseError while rendering: subquery returns more than 1 row.' I'm using PostGis.

my model

class Place(models.Model):    
    coordinate = models.PointField()

class TranslatedPlace(models.Model):
    place = models.ForeignKey(Place)

my view

  near_coordinates = Place.objects.filter(coordinate__distance_lte=(place_obj.coordinate, D(km=100)))
  near_places = TranslatedPlace.objects.filter(place=near_coordinates)

回答1:


I believe you'll want to use in to filter the second queryset

near_coordinates = Place.objects.filter(coordinate__distance_lte=(place_obj.coordinate, D(km=100)))
near_places = TranslatedPlace.objects.filter(place__in=near_coordinates)



回答2:


If Place.objects.filter(coordinate__distance_lte=(place_obj.coordinate, D(km=100))) is SUPPOSED to return multiple objects, you might be able to use near_places = TranslatedPlace.objects.filter(place__in=near_coordinates) note the __in for the place field. If you are only supposed to get one and there IS only one, you could do a .get() instead of .filter(). If there is more than one in the database, but you only want to get one, you could .filter(...)[0] to get the first one. Also, you could .filter(...).order_by('sort_field')[0] if you want to get the first one based on some sorting.



来源:https://stackoverflow.com/questions/8217490/query-of-a-subquery-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!