beni
beni

Reputation: 3029

Query of a subquery in Django

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)

Upvotes: 3

Views: 1905

Answers (2)

Furbeenator
Furbeenator

Reputation: 8285

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.

Upvotes: 3

Scott
Scott

Reputation: 506

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)

Upvotes: 6

Related Questions