使用tastypie从PointField返回纬度和经度值

dar*_*ren 4 python api django geodjango tastypie

使用django-tastypie v0.9.11 django 1.4.1geodjango.

在geodjango之前,我曾经将我的lat和lng值直接保存到我的模型中.然后,当我调用API时,我只是轻松地提取我的值.像这样的东西:

{
    "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"
},
Run Code Online (Sandbox Code Playgroud)

现在我已经升级了我的webapp以使用geodjango,现在我将我的信息存储在PointField()中.现在,如果我对我以前制作的API进行相同的调用,我会回复此:

{
    "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"
},
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,点值不同,因此我的移动应用程序正在破碎.

我的问题是如何从点数字段中获取纬度和经度值,并像以前一样使用查询集返回它们?

Dan*_*ezo 8

您需要覆盖您的dehydrate()方法,如http://django-tastypie.readthedocs.org/en/latest/cookbook.html#adding-custom-values中所述

所以这样的事情可能适合你:

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
Run Code Online (Sandbox Code Playgroud)

顺便说一句,tastypie的开发版本不久前得到了geodjango的支持,你可能会对它进行检查.这些文档可在http://django-tastypie.readthedocs.org/en/latest/geodjango.html上找到.