0
votes

I'm able to return the following response from my api sans the bold text.

{ "data": { "type": "users", "id": "2", "attributes": { "email": "[email protected]", "name": "first last", }, "relationships": { "businesses": { "data": { "type": "Business", "id": "1" "attributes": { "name": "the spot:, "address": "foo", } } },

I'm using Django Rest Framework JSON Api to format the response to JSON Api spec and I'm wondering what I need to do to get attributes added to the response in the relationship object. It would seem that the business serializer is the issue however their documentation isn't all that clear on how to get a response formatted like this as it instead shows how to get just the primary key of the business returned. Any ideas?

My serializer looks like this:

from rest_framework import serializers
from rest_framework_json_api import serializers as srs
from rest_framework_json_api.relations import ResourceRelatedField, SerializerMethodResourceRelatedField
from businesses.serializers import BusinessSerializer
from businesses.models import Business
from . import models

class UserSerializer(serializers.ModelSerializer):

    token = srs.SerializerMethodField()

    # necessary for M2M fields & reverse FK fields
    businesses = ResourceRelatedField(read_only=True, allow_null=True)

    review_user = ResourceRelatedField(read_only=True, allow_null=True, many=True)
    booking_user = ResourceRelatedField(read_only=True, allow_null=True, many=True)
    #businesses = serializers.PrimaryKeyRelatedField(queryset=Business.objects.all(), required=False)
    #businesses = BusinessSerializer(read_only=True)

    """Meta class tells Django what fields we want to take from the model"""
    class Meta:
        # links the serializer to the model class
        model = models.User
        # this is a tuple
        fields = ('id', 'email', 'password', 'name', 'phone', 'location', 'token', 'has_business', 'is_active', 'businesses')
        extra_kwargs = {'password': {'write_only': True}}
1

1 Answers

0
votes

It looks like the proper way to handle this issue is to make the following changes to my serializer:

1) Assign the business serializer to the related field:

businesses = BusinessSerializer(read_only=True)

2) This is what was really eluding me as I believe I nested this code inside my meta class while researching which didn't work. It should be nested inside the (in my case) UserSerializer but outside the meta class:

class JSONAPIMeta:
        included_resources = ['businesses']

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