Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Showing username and not ID, how?

I have the following serializers class.

class ProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = Profile
        fields = ('id', 'name', 'active', 'type', 'user')

When listing all profiles the user field shows the user ID. How do I change this to show the user.username? I know with my models I just add this to my meta class, but as did not create the user model (its part of Django). How do I tell Django when calling a user to show the username and not the id?

Many thanks.

like image 381
Prometheus Avatar asked Dec 12 '22 17:12

Prometheus


2 Answers

Two obvious ways you can deal with this:

Firstly you can use the dotted.notation to force the source argument of the user field to be user.username instead of the default user.

class ProfileSerializer(serializers.ModelSerializer):
    user = serializers.Field(source='user.username')

    class Meta:
        model = Profile
        fields = ('id', 'name', 'active', 'type', 'user')

Note that Field is a standard read-only field, so you wouldn't be able to update the user using this serializer.

Alternatively, if you want user to be a writable field, you can use a SlugRelatedField like so...

class ProfileSerializer(serializers.ModelSerializer):
    user = serializers.SlugRelatedField(slug_field='username')

    class Meta:
        model = Profile
        fields = ('id', 'name', 'active', 'type', 'user')

If you want you could also use the second approach but use a read-only field, by adding read_only=True to the SlugField.

like image 54
Tom Christie Avatar answered Dec 14 '22 08:12

Tom Christie


This thread is old, but since I encoutered the same issue recently I would like to add the modern answer to it. We must user the built-in SerializerMethodField() of DRF like this:

class ProfileSerializer(serializers.ModelSerializer):
  user = serializers.SerializerMethodField()

  def get_user(self, obj):
      return obj.user.username

  class Meta:
      model = Profile
      fields = ('id', 'name', 'active', 'type', 'user')
like image 38
Dr. Younes Henni Avatar answered Dec 14 '22 07:12

Dr. Younes Henni