2016-02-12 34 views
4

我使用Django的REST框架JSON API一個Django 1.9.2項目:如何在Django Rest Framework JSON API中生成JSON-API數據屬性與結果屬性?

https://github.com/django-json-api/django-rest-framework-json-api

我的視圖集中看起來是這樣的:

class QuestionViewSet(viewsets.ReadOnlyModelViewSet): 
    """ 
    API endpoint that allows questions and answers to be read. 
    """ 
    resource_name = 'questions' 
    queryset = Question.objects.all() 
    serializer_class = QuestionSerializer 
    renderers = renderers.JSONRenderer 
    parsers = parsers.JSONParser 

典型的反應是這樣的:

{"links": {"first": "http://testserver/api/v1/coaches?page=1", "last": "http://testserver/api/v1/coaches?page=1", "next": null, "prev": null}, "results": [{"id": 1, "created": "2016-02-11T02:41:22.569000Z", "updated": null, "deleted": null, "uuid": "0473c709-994f-465b-989e-407c623f365f", "user": {"type": "User", "id": "2"}}, {"id": 2, "created": "2016-02-11T02:41:46.853000Z", "updated": null, "deleted": null, "uuid": "36e19c0e-bda6-4bd7-bc73-374a6fc509d6", "user": {"type": "User", "id": "3"}}, {"id": 3, "created": "2016-02-11T02:42:05.419000Z", "updated": null, "deleted": null, "uuid": "d0798ff4-3be2-4cf3-81ac-edf8049eb075", "user": {"type": "User", "id": "4"}}], "meta": {"pagination": {"page": 1, "pages": 1, "count": 3}}} 

我希望輸出具有數據屬性而不是結果屬性。我怎麼能告訴輸出這裏所描述的風格DRF JSON API:

http://jsonapi.org/format/

回答

1

在我的情況的問題是,我有一個視圖集派生類這樣的觀點:

class QuestionViewSet(viewsets.ReadOnlyModelViewSet): 
    """ 
    API endpoint that allows questions and answers to be read. 
    """ 
    resource_name = 'questions' 
    queryset = Question.objects.all() 
    serializer_class = QuestionSerializer 
    renderers = renderers.JSONRenderer 
    parsers = parsers.JSONParser 

這是錯誤。渲染器和解析器屬性實際上分別是renderer_classes和parser_classes。此外,這些屬性的右值是元組,而不是單身人士。因此:

class QuestionViewSet(viewsets.ReadOnlyModelViewSet): 
    """ 
    API endpoint that allows questions and answers to be read. 
    """ 
    resource_name = 'questions' 
    queryset = Question.objects.all() 
    serializer_class = QuestionSerializer 
    renderer_classes = (renderers.JSONRenderer,) 
    parser_classes = (parsers.JSONParser,) 

這種變化之後,JSON API響應在很大程度上是正確的:

{"data":{"type":"questions","id":"1","attributes":{"created":"2016-02-10T04:28:50.742000Z","updated":null,"deleted":null,"uuid":"eddfc27d-2677-49e5-bd37-92fecea340bd","text":"Are you dizzy?"},"relationships":{"answers":{"data":[{"type":"Answer","id":"1"},{"type":"Answer","id":"2"},{"type":"Answer","id":"3"}]},"members":{"data":[{"type":"Member","id":"1"},{"type":"Member","id":"2"},{"type":"Member","id":"3"},{"type":"Member","id":"4"}],"meta":{"count":4}}}}} 
+0

所以問題變成與我所建議的不同?我很困惑:D – bmbigbang

0

我相信你必須創建一個自定義呈現與您的項目工作。下面是rest-framework renderers

引導我可以指出你在Response類JSON的模板的行一個快速和骯髒的解決辦法: ​​

+0

感謝您的答覆。這幫助我調試了上面提到的正確答案。 –

相關問題