yeti blue
yeti blue

Reputation: 271

How to Change Django AbstractUser Group to String

I made some groups inside of Django Admin, but whenever I add a user to one of those groups, only the group ID displays inside of my API endpoint. Is there a way to display the string name?

Adding Myself to Directors

It Shows up as 1 in the endpoint

So instead of 1, I want the field to be "Directors". Does it have anything to do with extending the AbstractUser Model?

This is all I have right now, for my User info:

class User(AbstractUser):
   

Serializer.py

from .models import User
class UserSerializer(serializers.ModelSerializer):
    class Meta:
        exclude = ["username", "password"]
        model = User

Upvotes: 1

Views: 158

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477676

You can make use of a SlugRelatedField [drf-doc] to serialize the groups:

from .models import User

class UserSerializer(serializers.ModelSerializer):
    # serialize groups with "slugs" ↓
    groups = serializers.SlugRelatedField(
        many=True,
        slug_field='name'
     )

    class Meta:
        exclude = ['username', 'password']
        model = User

Upvotes: 1

Related Questions