6

django-tastypie v0.9.11 django 1.4.1およびgeodjangoを使用します。

geodjango の前は、緯度と経度の値をモデルに直接保存していました。次に、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"
},

これで、 geodjangoを使用するように webapp をアップグレードし、情報を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"
},

ご覧のとおり、ポイント値が異なるため、モバイル アプリが壊れています。

私の質問は、ポイントフィールドから緯度と経度の値を取得し、以前のようにクエリセットで返すにはどうすればよいですか?

4

1 に答える 1

10

http://django-tastypie.readthedocs.org/en/latest/cookbook.html#adding-custom-valuesで説明されているように、 dehydrate()メソッドをオーバーライドする必要があります。

したがって、次のようなものがうまくいくかもしれません:

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

ちなみにtastypieの開発版は少し前にgeodjangoに対応したので調べてみると面白いかもしれません。ドキュメントはhttp://django-tastypie.readthedocs.org/en/latest/geodjango.htmlで入手できます。

于 2012-09-06T13:35:26.763 に答える