How to generate JSON-API data attribute vs results attribute in Django Rest Framework JSON API?

2024/10/11 13:28:16

I have a django 1.9.2 project using Django Rest Framework JSON API:

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

My viewset looks like this:

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

Typical response looks like this:

{"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}}}

I want the output to have a data attribute as opposed to the results attribute. How can I tell DRF JSON API to output the style described here:

http://jsonapi.org/format/

Answer

The problem in my case was that I had a viewset derived class in the view like this:

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

This is wrong. The renderers and parsers attributes are actually renderer_classes and parser_classes, respectively. Moreover, the rvalues of those attributes are tuples, not singletons. Thus:

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

After this change, the JSON API response is largely correct:

{"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}}}}}
https://en.xdnf.cn/q/69769.html

Related Q&A

How connect my GoPro Hero 4 camera live stream to openCV using Python?

I m having troubles trying to capture a live stream from my new GoPro Hero 4 camera and do some image processing on it using openCV.Here is my trial (nothing shows up on the created windowimport cv2 im…

I thought Python passed everything by reference?

Take the following code#module functions.py def foo(input, new_val):input = new_val#module main.py input = 5 functions.foo(input, 10)print inputI thought input would now be 10. Why is this not the cas…

Python: -mno -cygwin

im trying to learn a lot of python on windows and that includes installing several packages, however everytime i invoke python setup.py install i have a problem with -mno -cygwin for gcc. ive have rea…

Django Sites Framework initial setup

Im comfortable with fairly one-dimensional Django implementations, but now trying to understand the multi-sites-with-shared-stuff process. Ive read through the Django Sites Framework and many posts o…

Data corruption: Wheres the bug‽

Last edit: Ive figured out what the problem was (see my own answer below) but I cannot mark the question as answered, it would seem. If someone can answer the questions I have in my answer below, name…

Python NetworkX — set node color automatically based on a list of values

I generated a graph with networkx import networkx as nx s = 5 G = nx.grid_graph(dim=[s,s]) nodes = list(G.nodes) edges = list(G.edges) p = [] for i in range(0, s):for j in range(0, s):p.append([i,j])…

control wspace for matplotlib subplots

I was wondering: I have a 1 row, 4 column plot. However, the first three subplots share the same yaxes extent (i.e. they have the same range and represent the same thing). The forth does not. What I w…

Getting indices of both zero and nonzero elements in array

I need to find the indicies of both the zero and nonzero elements of an array.Put another way, I want to find the complementary indices from numpy.nonzero().The way that I know to do this is as follows…

tweepy how to get a username from id

how do I derrive a plaintext username from a user Id number with tweepy? Here is the CORRECTED code that I am using:ids = [] userid = "someOne" for page in tweepy.Cursor(api.followers_ids, s…

How to select many to one to many without hundreds of queries using Django ORM?

My database has the following schema:class Product(models.Model):passclass Tag(models.Model):product = models.ForeignKey(Product)attr1 = models.CharField()attr2 = models.CharField()attr3 = models.CharF…