Search code examples
djangodjango-rest-frameworkdjango-serializer

How to flatten serialized data with only 1 field in Django Rest Framework


I have the following serializer:

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ("username", "profile_picture")

class SomeSerializer(serializers.ModelSerializer):
    some_user = UserSerializer()

    class Meta:
        model = UserFollowing
        fields = ("some_user",)

And the model UserFollowing associated to it:

class UserFollowing(models.Model):
    some_user = models.ForeignKey(User, on_delete=models.CASCADE)

The serializer returns something like this:

[
    {
        "some_user": {
            "username": "jane",
            "profile_picture": "/media/picture.jpg"
        }
    },
    ...
]

For consistency and simplicity, I would like to return:

[
    {
        "username": "jane",
        "profile_picture": "/media/picture.jpg"
    },
    ...
]

How can I achieve this?


Solution

  • You can use serializerMethodField:

    class SomeSerializer(serializers.ModelSerializer):
        username = serializers.SerializerMethodField()
        profile_picture = serializers.SerializeMethodField()
    
        def get_username(self, obj):
            return obj.some_user.username
        
        def get_profile_picture(self, obj):
            return obj.some_user.profile_picture
    
        class Meta:
            model = UserFollowing
            fields = ("username", "profile_picture")