hY8vVpf3tyR57Xib
hY8vVpf3tyR57Xib

Reputation: 3915

Serializing user groups as an array without keywords in Django Rest Framework

I am working on a Django project with the django_rest_framework. I am trying to create a serializer that returns a user with all the groups that he belongs to as a simple array.

For example:

{
   "username": "John Doe",
   "groups": "[Group1, Group2]"
}

My current configuration however returns the groups as objects and adds attribute names, so my previous example unfortunately returns as follows:

{
   "username": "John Doe",
   "groups": "[{"name":"Group1"},{"name":"Group2"}]"
}

Are you able to get the achieve the result that I want with the django_rest_framework? Here are my serializers:

serializers.py

from django.contrib.auth.models import User, Group
from rest_framework import serializers


class GroupSerializer(serializers.ModelSerializer):
    class Meta:
        model = Group
        fields = ('name',)


class UserSerializer(serializers.ModelSerializer):
    groups = GroupSerializer(many=True)

    class Meta:
        model = User
        fields = ('username', 'groups')

Upvotes: 1

Views: 1434

Answers (2)

Dima  Kudosh
Dima Kudosh

Reputation: 7376

You can use SerializerMethodField.

class UserSerializer(serializers.ModelSerializer):
    groups = SerializerMethodField()

    class Meta:
        model = User
        fields = ('username', 'groups')

    def get_groups(self, obj):
        return [group.name for group in obj.groups]

Upvotes: 6

neverwalkaloner
neverwalkaloner

Reputation: 47354

Try to override GroupSerializer's to_representation method:

class GroupSerializer(serializers.ModelSerializer):
    class Meta:
        model = Group
        fields = ('name',)

    def to_representation(self, obj):
        return obj.name

Didn't test it, please check if this work.

Upvotes: 0

Related Questions