pythondjangodjango-rest-frameworkdjango-4.0

Add extra property to this json response returned by Django rest framework


I am running django 4.0.6 with djangorestframework.

This is my serializers.py

from django.contrib.auth import get_user_model
from rest_framework import serializers


class UserSerializer(serializers.ModelSerializer):  # new
    class Meta:
        model = get_user_model()
        fields = (
            "id",
            "username",
        )

This is my views.py

from django.contrib.auth import get_user_model
from rest_framework import generics

from .serializers import UserSerializer


class UserList(generics.ListCreateAPIView):
    queryset = get_user_model().objects.all()
    serializer_class = UserSerializer

Here is the json response of the API;

{
    "count": 3,
    "next": null,
    "previous": null,
    "results": [
        {
            "id": 1,
            "username": "test"
        },
        {
            "id": 4,
            "username": "test1"
        },
        {
            "id": 8,
            "username": "test3"
        }
    ]
}

I would like to add an extra property to this json response returned by Django rest framework such that it will look like this;

{
    "count": 3,
    "next": null,
    "previous": null,
    "results": [
        {
            "id": 1,
            "username": "test"
            "combine" : "test 1"
        },
        {
            "id": 4,
            "username": "test1"
            "combine" : "test1 4"
        },
        {
            "id": 8,
            "username": "test3"
            "combine" : "test3 8"
        }
    ]
}

The extra property combine is created by concatenating id and username.


Solution

  • You can use a SerializerMethodField:

    class UserSerializer(serializers.ModelSerializer):
        combine = serializers.SerializerMethodField()
    
        class Meta:
            model = get_user_model()
            fields = (
                "id",
                "username",
                "combine",
            )
    
        def get_combine(self, obj):
            return f"{obj.username} {obj.id}"