0

I have a Django model that has many=True nesting, and I'd like to serializer the nested objects (in Django Rest Framework) as an object instead of a list (which is the default in DRF).

Adding many=True serializes things as a list.

class PostSerializer(serializers.ModelSerializer):
  votes = VoteSerializer(many=True)

Instead of rendering the votes as a list of objects:

[... posts: [{id: 123, user: A}, {id: 456, user: B}, ....]

I'd like to render votes as a list of objects keyed by id:

[... posts: {123: {user: A}, 456: {user: B}}, ...]

1 Answer 1

1

This is poking into a private API and isn't exactly concise, but should work.

class DictManyRelatedField(serializers.ManyRelatedField):
    def to_representation(self, iterable):
        return {
           value.pk: self.child_relation.to_representation(value)
           for value in iterable
        }


class VoteSerializer(serializers.ModelSerializer):
    user = serializers.CharField()

    class Meta:
        model = Vote
        fields = ('user',)

    @classmethod
    def many_init(cls, *args, **kwargs):
        kwargs['child_relation'] = cls()
        return DictManyRelatedField(*args, **kwargs)


class PostSerializer(serializers.ModelSerializer):
    votes = VoteSerializer(read_only=True, many=True)

    class Meta:
        model = Post
        fields = ('votes',)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.