Search code examples
pythondjangoapitastypiegeodjango

Return Latitude and Longitude values from a PointField using tastypie


Using django-tastypie v0.9.11 django 1.4.1 and geodjango.

Before geodjango I used to save my lat and lng values straight into my model. Then when I'd call the API I'd just pull my values easily. Something like this:

{
    "id": "1",
    "lat": "-26.0308215267084719",
    "lng": "28.0101370772476450",
    "author": "\/api\/v1\/user\/3\/",
    "created_on": "2012-07-18T14:33:31.081105",
    "name": "qweqwe",
    "updated_on": "2012-09-06T14:17:01.658947",
    "resource_uri": "\/api\/v1\/spot\/1\/",
    "slug": "qweqwe"
},

Now I've upgraded my webapp to use geodjango and I now store my information in a PointField(). Now if I make the same call to the API that I used to make I get back this:

{
    "id": "1",
    "point": "POINT (28.0101370772476450 -26.0308215267084719)",
    "author": "\/api\/v1\/user\/3\/",
    "created_on": "2012-07-18T14:33:31.081105",
    "name": "qweqwe",
    "updated_on": "2012-09-06T14:17:01.658947",
    "resource_uri": "\/api\/v1\/spot\/1\/",
    "slug": "qweqwe"
},

As you can see the point value is different and so my mobile apps are breaking.

My question is how can I get the latitude and longitude values out of the point field and return them with the queryset like before?


Solution

  • You need to override your dehydrate() method, as described at http://django-tastypie.readthedocs.org/en/latest/cookbook.html#adding-custom-values

    So something like this might work for you:

    class MyModelResource(Resource):
        class Meta:
            qs = MyModel.objects.all()
    
        def dehydrate(self, bundle):
            # remove unneeded point-field from the response data
            del bundle.data['point']
            # add required fields back to the response data in the form we need it
            bundle.data['lat'] = bundle.obj.point.y
            bundle.data['lng'] = bundle.obj.point.x
            return bundle
    

    By the way, the development version of tastypie got support for geodjango a while ago and it might be interesting for you to check it out. The docs are available at http://django-tastypie.readthedocs.org/en/latest/geodjango.html