Distance Spatial Queries with Tastypie

半世苍凉 提交于 2019-12-12 01:45:51

问题


Not sure how to use distance_lte spatial filters with tasty-pie. I can use the contains spatial filter i am unable to figure out the format for the distance_lte filter.

Here is what I have tried:

http://www.domain.com/myapp/api/v1/location/?format=json&coord__distance_lte={"type": "Point", "coordinates": [153.09537, -27.52618]},D(m=5)

Which returns {"error": "Invalid resource lookup data provided (mismatched type)."}


回答1:


From the tastypie sourcecode:

# If we are filtering on a GeometryApiField then we should try
# and convert this to a GEOSGeometry object.  The conversion
# will fail if we don't have value JSON, so in that case we'll
# just return ``value`` as normal.

your D(m=3) is not valid JSON. This is the Code that is translating the fields:

if isinstance(self.fields[field_name], GeometryApiField):
        try:
            value = GEOSGeometry(unquote(value))
        except ValueError:
            pass
    return value

Since the following Code should work internally: Location.objects.filter(location__distance_lte=(fromstr('POINT(153.09537 -27.52618)', srid=4326), D(m=5)))

I could imagine it would need to look a little like:

[{"type": "Point", "coordinates": [153.09537, -27.52618]},{"type": "D", "m" : 5}]

I am not yet getting this to run. Hope you have more luck with it!

EDIT: Since I couldn't get this to run, I implemented it myself using Django Tastypie Advanced Filtering: How to do complex lookups with Q objects Not the ideal solution, but it works.




回答2:


This is because Tastypie erroneously looks for valid filters using the querysets query.query_terms attributes

It won't contain 'distance', and as a result you get the error.

Except for contains, TastyPie is mostly non-functional with these GIS searches (at least without adding in your own special sauce.)

You could make distance work, for example, by overriding build_filters and adding 'distance' to the valid set of filters:

def build_filters(self, filters=None):
   '''
   Add in some filters so spatial queries will work.
   '''
   self._meta.queryset.query.query_terms.update(set(['distance','distance_lte']))
   return super(MyResource, self).build_filters(filters)

After which the documentation starts to become correct in regard to how you pass in WKT and/or GeoJSON as get parameters.



来源:https://stackoverflow.com/questions/23429263/distance-spatial-queries-with-tastypie

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