[Fixed]-GeoDjango, difference between dwithin and distance_lt?


Ok, I did some research but I don’t know if the results are of any use 😉

  • I looked at the unit tests that they use to test the DB queries but they don’t give real hints (to me).

  • I tried to compare the generated SQL:

I have already a geo application using a PostgreSQL databse. When I perform this query with __distance_lt:

Place.objects.filter(location__distance_lt=(p.location, D(km=1))).query.as_sql()

I get this generated SQL:

SELECT (some_fields_here)
FROM "places_place" 
WHERE ST_distance_sphere("places_place"."location", %s) < 1000.0

When I try to use do to the same with __dwithin, I get an error:

Place.objects.filter(location__dwithin=(p.location, D(km=1))).query.as_sql()

TypeError: Only numeric values of degree units are allowed on geographic DWithin queries.

So I had to change the query to no use a D object:

Place.objects.filter(location__dwithin=(p.location, 1)).query.as_sql()

which results in

SELECT (some fields here) 
FROM "places_place" 
WHERE ST_DWithin("places_place"."location", %s, 1)


– takes degree values as distance parameter.
– uses ST_DWithin SQL function.

– can take other distance values ;).
– uses ST_distance_sphere SQL function.

Btw, I get different results with both queries but I guess this is mostly due the fact that I don’t know which “degree” value to use.

Leave a comment