[Fixed]-How to serialize groups of a user with Django-Rest-Framework

42👍

You have to specify that it’s a nested relationships:

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

class UserSerializer(serializers.ModelSerializer):    
    groups = GroupSerializer(many=True)
    class Meta:
        model = User
        fields = ('url', 'username', 'email', 'is_staff', 'groups',)

Check documentation for more information : Nested relationships

6👍

Something like this should work.

from django.contrib.auth.models import Group


class UserSerializer(serializers.ModelSerializer): 
    groups = serializers.SlugRelatedField(
        many=True,
        read_only=True,
        slug_field='name',
     )  
 
    class Meta:
        model = User
        fields = ('url', 'username', 'email', 'is_staff', 'groups',)

Leave a comment