Question

Is it possible to query a django model by the lng, lat values of a PointField?

<---example--->

Foo.objects.filter(bar=(-73, 34)) 

## bar == name of PointField in the django model.
## -73 == longitude
## 34 == latitude
Was it helpful?

Solution

Checking exact matches with coordinates might not be a good idea. You should query with the distance from the provided coordinates. Anyway, you can do both. From the documentation, there are many lookups you can perform on PointField. You can use the distance filter like this -

>>> from django.contrib.gis.geos import *
>>> from django.contrib.gis.measure import D # ``D`` is a shortcut for ``Distance``
>>> from geoapp import SouthTexasCity
# Distances will be calculated from this point, which does not have to be projected.
>>> pnt = fromstr('POINT(-96.876369 29.905320)', srid=4326)
# If numeric parameter, units of field (meters in this case) are assumed.
>>> qs = SouthTexasCity.objects.filter(point__distance_lte=(pnt, 7000))
# Find all Cities within 7 km, > 20 miles away, and > 100 chains  away (an obscure unit)
>>> qs = SouthTexasCity.objects.filter(point__distance_lte=(pnt, D(km=7)))
>>> qs = SouthTexasCity.objects.filter(point__distance_gte=(pnt, D(mi=20)))
>>> qs = SouthTexasCity.objects.filter(point__distance_gte=(pnt, D(chain=100)))

Similarly you can perform exact lookup.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top