简体   繁体   中英

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

I'm trying to get users groups with Django REST framework, but only what I got is empty field named "groups".

This is my UserSerializer:

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

any ideas how to get users groups data?

thanks in advance

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

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',)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM