question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Nested serializers only work with Django Model objects

See original GitHub issue

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.

Issue Analytics

  • State:closed
  • Created 7 years ago
  • Comments:9 (9 by maintainers)

github_iconTop GitHub Comments

1reaction
knaperekcommented, Jun 3, 2016

@adaptivdesign Thanks for such a prompt fix, I confirm that it no longer crashes.

However, I’m still missing the included top level key (with its data). Is this a missing feature in general, or is it pertinent to this Model-less setup? UPDATE: OK, included works when added as a query param inside the request. Would be nice to have the ability to set the default included types though.

Anyway, many thanks for help and quick fixing! You guys rock 👍

This is my output currently:

{
  "data": {
    "type": "users",
    "id": "tmp-953157",
    "attributes": {
      "name": "Bob"
    },
    "relationships": {
      "posts": {
        "data": [
          {
            "type": "post",
            "id": "tmp-545551"
          },
          {
            "type": "post",
            "id": "tmp-612679"
          }
        ]
      }
    }
  }
}

UPDATE 2: I have created PR #250 that implements this new option to specify resources to be included by default.

1reaction
rmmrcommented, Jun 2, 2016

Just came across the same issue. I will fix this in the coming hours. Pull request incoming.

Read more comments on GitHub >

github_iconTop Results From Across the Web

django - Avoid nested objects when using nested serializers
Use SerializerMethodField from rest_framework.fields import SerializerMethodField class ModelTwoSerializer(serializers.
Read more >
Nested Serializers in Django Rest Framework - Dev Genius
Here I'm going to use nested serializers. The serializers in the REST framework work very similarly to Django's Form and ModelForm classes.
Read more >
Serializer relations - Django REST framework
If you wish to represent extra fields on a through model then you may serialize the through model as a nested object.
Read more >
Django Rest Framework Serializer not printing nested ...
I've created serializers for both of them following the DRF documentation, yet when printing the serializer.data the nested objects don't show.
Read more >
Serializers - Django REST framework - Tom Christie
Serializers allow complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found