Skip to content

Nested serializers only work with Django Model objects #249

@knaperek

Description

@knaperek

While DRF works perfectly fine with simple non-model instances, DJA crashes and can't be made to work correctly.

For example, this code works fine with DRF:

import random
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_json_api import serializers
from rest_framework_json_api.renderers import JSONRenderer as jsonapi_renderer


class Post(object):
    def __init__(self, message):
        super(Post, self).__init__()
        self.pk = 'tmp-%s' % random.randint(1, 2**20)  # Added to support json API referencing
        self.message = message


class User(object):
    def __init__(self, name, posts):
        super(User, self).__init__()
        self.pk = 'tmp-%s' % random.randint(1, 2**20)  # Added to support json API referencing
        self.name = name
        self.posts = posts


class PostSerializer(serializers.Serializer):
    message = serializers.CharField(max_length=200)


class UserSerializer(serializers.Serializer):
    name = serializers.CharField(max_length=200)
    posts = PostSerializer(many=True, read_only=True)


class UserView(APIView):
    resource_name = 'users'
    renderer_classes = (jsonapi_renderer,)  # ! Uncommenting this causes failure !

    def get(self, request, format=None):
        p1 = Post("First message")
        p2 = Post("Second message")
        user = User('Bob', [p1, p2])
        s = UserSerializer(user)
        return Response(s.data)

However, after uncommenting the line that specifies the JSON API renderer class to be used, the view crashes with:

'NoneType' object has no attribute 'Meta'

If DJA does not support Model-less references, it could at least be clearly stated in the documentation, mentioning also some workarounds if such exist. Though, I have not found any way to make this working yet.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions