Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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}"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading