3

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)
beni
  • 3,019
  • 5
  • 35
  • 55

2 Answers2

6

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)
Scott
  • 506
  • 4
  • 8
3

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.

Furbeenator
  • 8,106
  • 4
  • 46
  • 54