0

I have an api in django-rest framework that now returns this json data:

  [
    {
        "id": 1,
        "foreignobject": {
            "id": 3
        },
        "otherfields": "somevalue"
    }
]

But I want it to return something like this (flatten the foreigneky to its ID only):

[
    {
        "id": 1,
        "foreignobject_id":3,
        "otherfields": "somevalue"
    }
]

Doing this in the model Resource, now I Have (simplified):

class ForeignKeyInDataResource(ModelResource):
    model = TheOtherModel
    fields = ('id',)


class SomeModelResource(ModelResource):
    model = SomeModel
    fields = ( 'id',('foreignobject','ForeignKeyInDataResource'),'otherfields',)

I tried already something like:

class SomeModelResource(ModelResource):
    model = SomeModel
    fields = ( 'id','foreignobject__id','otherfields',)

but that did not work

for the complete story, this how the view returns the data, list is a result of a query over the SomeModel:

data = Serializer(depth=2 ).serialize(list)
return Response(status.HTTP_200_OK, data)
4

2 に答える 2

1

私はもう REST フレームワーク 0.x をサポートする立場にはありませんが、2.0 にアップグレードすることに決めた場合、これは簡単です。単純にシリアライザーでフィールドを次のように宣言します。foreignobject = PrimaryKeyRelatedField()

于 2012-11-20T13:43:19.253 に答える
1

別のオプションを見つけました: (ModelResource のドキュメントを読むことで...) Modelresource では、ID を返すことができる関数 (self,instance) を定義できます。

フィールドにこの機能を追加できます!

したがって、これは機能します:

class SomeModelResource(ModelResource):
    model = SomeModel
    fields = ( 'id','foreignobject_id','otherfields',)

    def foreignobject_id(self, instance):
        return instance['foreignobject']['id']
于 2012-11-20T16:17:36.750 に答える