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
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.
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.
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.
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',)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With