Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 262
kml Avatar asked Nov 21 '15 13:11

kml


People also ask

What is serialization in Django REST Framework?

Serializers in Django REST Framework are responsible for converting objects into data types understandable by javascript and front-end frameworks. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.

What is the difference between ModelSerializer and HyperlinkedModelSerializer?

The HyperlinkedModelSerializer class is similar to the ModelSerializer class except that it uses hyperlinks to represent relationships, rather than primary keys. By default the serializer will include a url field instead of a primary key field.

What is To_representation in Django serializer?

to_representation(self, value) method. This method takes the target of the field as the value argument, and should return the representation that should be used to serialize the target. The value argument will typically be a model instance.


1 Answers

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',)
like image 129
ronniesh Avatar answered Oct 02 '22 03:10

ronniesh