Reputation: 1211
I'm trying to show user group name instead of it's id .
I have this serilizer class for user class and I used this User = auth.get_user_model()
for user Model
but it show NULL instead of theier name .. when i delete get_groups function i will see related groups id why ?
what is correct way to get all users group?
class UserSerializer(ModelSerializer):
groups = SerializerMethodField()
def get_groups(self, obj):
return obj.groups.name
class Meta:
model = User
fields = [
'id',
'username',
'first_name',
'last_name',
'email',
'date_joined',
'last_login',
'is_staff',
'is_superuser',
'is_active',
'groups'
]
Upvotes: 1
Views: 981
Reputation: 88539
Try this,
class UserSerializer(ModelSerializer):
def get_groups(self, obj):
return obj.groups.values_list('name', flat=True)
class Meta:
model = User
fields = [
'id',
'username',
'first_name',
'last_name',
'email',
'date_joined',
'last_login',
'is_staff',
'is_superuser',
'is_active',
'groups'
]
This would return all grups related to paricular user as list
Example:
In [5]: user =User.objects.get(id=1)
In [6]: user.groups.values_list('name',flat=True)
Out[6]: ['grp_name_1', 'grp_name_2']
In [8]: user.groups.all()
Out[8]: [<Group: grp_name_1>, <Group: grp_name_2>]
Upvotes: 1
Reputation: 2057
try it
groups = serializers.SlugRelatedField(many=True, read_only=True, slug_field="name")
Upvotes: 2