Modifying serializer response in Django Rest Framework


I am working on a DRF serializer for connection with an external service, i.e. an interface. I want to apply some transformations to my objects before serialising them and sending them and to do this I need to look at the whole queryset : I cannot treat each item individually. Essentially I want to group them and provide information about their grouping in the serialisation without changing the data in the database.

I am thinking of doing this :

  • Compiling the queryset normally in the view
  • Adding logic to the __init__() method of the serialiser to modify the instance data without saving the modifications back to the database.
  • Serving the data normally in the serialiser.

Is there a more Djangonic way to do this or a hook somewhere in the view or serializer that I have not spotted?



Yes, there is a more Django-esque way to achieve this behavior in your serializer. Instead of modifying the instance data in the __init__() method of your serializer, you can override the to_representation() method. This method is called by DRF just before serializing the data and gives you an opportunity to modify the data in any way you want.

Here’s an example of how you could use to_representation() to group your queryset and add information about the grouping to the serialized data:

class MySerializer(serializers.ModelSerializer):
def to_representation(self, instance):
# Group the queryset by some criteria (e.g. date)
grouped_data = {}
for obj in instance:
key =‘%Y-%m-%d’)
if key not in grouped_data:
grouped_data[key] =

    # Add grouping information to each item in the group
    serialized_data = []
    for key, group in grouped_data.items():
        for obj in group:
            obj.group_info = {'group_key': key, 'group_count': len(group)}

    return serialized_data
1 Like

Ahh - awesome, thank you very much, that’s perfect !

Actually this does not work for me - to_representation only gives me the objects one at a time without giving me the option to access all of the objects together, as far as I can see. Specifically it tells me that instance is not iterable.

I could access the queryset via the context but overloading __init__ looks like it may solve the first problem better.