Geo support with Django Rest Framework

512 views
Skip to first unread message

Sanjay Bhangar

unread,
Oct 20, 2013, 2:06:26 PM10/20/13
to django...@googlegroups.com
Hi all,

I'm developing an app using GeoDjango that requires me to create an
API. Ideally, I would output GeoJSON at various API end-points and
support a few geo-queries like "within bounding box", etc.

I have done something similar before without Django Rest Framework and
just writing vanilla views, but I thought it would be nice to make use
of a lot of the niceties that the framework provides.

Just wondering if something has dealt with serialization /
deserialization of geo models using Django Rest Framework and has any
pointers / code to share (or advice on why this is a bad idea :)). A
fair amount of internet searching did not turn up anything for me.

Looking through the docs, it seems like there are reasonable hooks to
write custom Serializer, Renderer and Filter classes - just wondering
if someone has gone down this road before - and also, potentially, if
someone else may find this useful and then I could think about making
whatever solution I come up with more generalizable ..

Also, if there's a better place to discuss this, please let me know :)

Thanks,
Sanjay

Tom Christie

unread,
Oct 21, 2013, 8:20:55 AM10/21/13
to django...@googlegroups.com
Hi Sanjay,

I would take a look at these two repos:


You might also try searching the REST framework issue list as it's likely either or both of these were at some point discussed there.
Also try searching the archives for the REST framework discussion group, here:


Hope that helps!

  Tom

rok

unread,
Oct 21, 2013, 10:28:52 AM10/21/13
to django...@googlegroups.com
I'm using tastypie for the REST functionality which I have extended so that geolocation can be used as a filter, e.g.:

class TestResource(ModelResource):
    
    class Meta:
        queryset = Event.objects.all()
        resource_name='test'
        ordering = ['date_from']
        
    def get_object_list(self, request):
        _items = super(TestResource, self).get_object_list(request).all()
        if request.method == 'GET':
            if 'lat' in request.GET and 'lng' in request.GET and 'rad' in request.GET:
                _lat = float(request.GET['lat'].strip())
                _lng = float(request.GET['lng'].strip())
                self._current_location = Point(_lat, _lng)
                _items=_items.filter(
                        Q(city__coordinates__distance_lte=(self._current_location, float(request.GET['rad'].strip())*1000))
                    )                    
        return _items                

    def dehydrate(self, bundle):
        bundle.data['lat'] = bundle.obj.city.coordinates.x
        bundle.data['lng'] = bundle.obj.city.coordinates.y
        bundle.data['distance'] = bundle.obj.city.coordinates.distance(self._current_location) * 100
        return bundle
      
Hope this helps, if you want I can include more code details...  
Rok

Sanjay Bhangar

unread,
Oct 21, 2013, 10:49:35 AM10/21/13
to django...@googlegroups.com
Hey Tom,

On Mon, Oct 21, 2013 at 1:50 PM, Tom Christie <christ...@gmail.com> wrote:
> Hi Sanjay,
>
> I would take a look at these two repos:
>
> https://github.com/dmeehan/django-rest-framework-gis
> https://github.com/mjumbewu/django-rest-framework-gis
>

This is EXACTLY what I was looking for. Obviously, I need to work on
my internet searching skills :/

Turns out things were fairly simple to do and I implemented what I
needed anyways, but this is obviously a bit cleaner so I will plug in
one of these. Essentially, a GeoJSON Serializer is what I was looking
for, and these give me exactly that :)

> You might also try searching the REST framework issue list as it's likely
> either or both of these were at some point discussed there.
> Also try searching the archives for the REST framework discussion group,
> here:
>
> https://groups.google.com/forum/#!forum/django-rest-framework
>

Yea, I saw their google forum link after I sent my mail here as well.
My apologies for not hunting enough before asking here.

Thanks again, and if folks from the django rest framework team are
reading this - you guys rock, it's been a pleasure to get into.

> Hope that helps!
>

Tremendously!
Thanks,
Sanjay


> Tom
>
> On Sunday, 20 October 2013 15:06:26 UTC+1, Sanjay Bhangar wrote:
>>
>> Hi all,
>>
>> I'm developing an app using GeoDjango that requires me to create an
>> API. Ideally, I would output GeoJSON at various API end-points and
>> support a few geo-queries like "within bounding box", etc.
>>
>> I have done something similar before without Django Rest Framework and
>> just writing vanilla views, but I thought it would be nice to make use
>> of a lot of the niceties that the framework provides.
>>
>> Just wondering if something has dealt with serialization /
>> deserialization of geo models using Django Rest Framework and has any
>> pointers / code to share (or advice on why this is a bad idea :)). A
>> fair amount of internet searching did not turn up anything for me.
>>
>> Looking through the docs, it seems like there are reasonable hooks to
>> write custom Serializer, Renderer and Filter classes - just wondering
>> if someone has gone down this road before - and also, potentially, if
>> someone else may find this useful and then I could think about making
>> whatever solution I come up with more generalizable ..
>>
>> Also, if there's a better place to discuss this, please let me know :)
>>
>> Thanks,
>> Sanjay
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users...@googlegroups.com.
> To post to this group, send email to django...@googlegroups.com.
> Visit this group at http://groups.google.com/group/django-users.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/71f87a56-b0ff-4ff7-9d4c-b47f4bb525f3%40googlegroups.com.
> For more options, visit https://groups.google.com/groups/opt_out.

Sanjay Bhangar

unread,
Oct 21, 2013, 11:01:37 AM10/21/13
to django...@googlegroups.com
Hi Rok,

Thank you so much for the reply and code snippets. I think I managed
to implement the stuff I needed using the hooks provided by
Django-Rest-Framework -- not 100% sure why I picked that over Tastypie
for this, but its treating me well, so I'll stick to it ..

Since we're sharing code :), this is what I came up with to handle
filtering by bbox and distance to a point -- this is obviously first
draft code, but it seemed to work quite well --

class VirtualCacheList(generics.ListAPIView):
serializer_class = VirtualCacheListSerializer

def get_queryset(self):
qset = VirtualCache.objects.all()
params = self.request.QUERY_PARAMS
username = params.get('username', None)
if username is not None:
qset = qset.filter(user__username=username)
bbox_string = params.get('bbox', None)
if bbox_string:
bbox = [float(b) for b in bbox_string.split(",")]
qset = qset.filter(point__within=bbox)
distance = params.get("distance", None)
lat = params.get("lat", None)
lon = params.get("lon", None)
if distance and lat and lon:
lat = float(lat)
lon = float(lon)
distance = int(distance)
point = Point(lat, lon)
qset = qset.filter(point__distance_lte=(point,
D(m=distance),)).distance(point, field_name='point')
qset = qset.order_by('distance')
return qset

I probably want to implement that as a Filter class or so - I will
look at the django-restframework-gis packages for an idea of the
cleanest way to do it, but it's super nice how easy these frame-works
have made it to get a fully functional api with docs and everything.
I'll probably bug the people over at the Django Rest Framework mailing
list if I run into issues, but so far I found ways to do everything I
needed to do - just the GeoJSON serialization seemed awkward, but I
see there's a package for that, so I seem to be sorted.

Thanks again,
Sanjay
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users...@googlegroups.com.
> To post to this group, send email to django...@googlegroups.com.
> Visit this group at http://groups.google.com/group/django-users.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/fe94c4c1-2883-4214-92d2-84b68a787713%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages