0

I'm trying to integrate support for an external library in my project. The external library requires a precise data structure that it uses to call response-as-a-table.

A simple serializer for my model, could be:

class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = ('id', 'title', 'author')

So, supposing a snippet like this:

queryset = Book.objects.all()
serializer = BookSerializer(queryset, many=True)
serializer.data

Which gives this output:

[
    {'id': 0, 'title': 'The electric kool-aid acid test', 'author': 'Tom Wolfe'},
    {'id': 1, 'title': 'If this is a man', 'author': 'Primo Levi'},
    {'id': 2, 'title': 'The wind-up bird chronicle', 'author': 'Haruki Murakami'}
]

How should I reshape my BookSerializer class to achieve this result? I can't figure it out.

{
    'id': [0, 1, 2],
    'title': ['The electric kool-aid acid test', 'If this is a man', 'The wind-up bird chronicle'],
    'author': ['Tom Wolfe', 'Primo Levi', 'Haruki Murakami']
}
4
  • 1
    Why do you want this behavior? Looks like you can do that in your view just by building your dict by iterating on queryset and not using serializers. But I am not sure that is a good way. Commented Oct 11, 2018 at 11:17
  • I need this behavior because a plotting library requires this data structure :( Commented Oct 11, 2018 at 11:17
  • @MilesDavis As Chiefir mentioned, you could do it in the view level. Commented Oct 11, 2018 at 12:18
  • just convert your queryset, you don't need serializer Commented Oct 11, 2018 at 13:05

1 Answer 1

1

Override the serializer's to_representation to reshape of the output dict however you want. DRF does not have such a utility, but you could easily achieve this with pandas. For example:

import pandas as pd

def to_representation(self, instance):
    data = super(BookSerializer, self).to_representation(instance)
    df = pd.DataFrame(data=data)
    reshaped_data = df.to_dict(orient='list')
    return reshaped_data

Note that now the shape of the data will not work if you want to use this serializer as part of a view.

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.