[Fixed]-DRF: data structure in serializer or view?

1👍

The schema you attached can (and should) be generated using Django REST Framework Serializers; the nested elements of your schema can be generated using nested serializers. Generally these serializers will inherit from the ModelSerializer.

Here is an example of the nested serializers you would use to begin to construct your schema:

class WordSerializer(serializers.ModelSerializer):
    """Serializer for a Word"""
    definitions = DefinitionSerializer(many=True)

    class Meta:
        model = Word
        fields = ('word', 'definitions')

class DefinitionSerializer(serializers.ModelSerializer):
    """Serializer for a Definition"""
    user = UserSerializer(read_only=True)
    votes = VoteSerializer(many=True)

    class Meta:
        model = Word
        fields = ('definition', 'user', 'votes')

One part of the schema you have listed which may be more complicated is the map of vote category to vote count. DRF naturally would create a structure which is a list of objects rather than a single object as your schema has. To override that behavior you could look into creating a custom ListSerializer.

Leave a comment