Prometheus
Prometheus

Reputation: 33655

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.

Upvotes: 4

Views: 5210

Answers (2)

Dr. Younes Henni
Dr. Younes Henni

Reputation: 1771

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')

Upvotes: 5

Tom Christie
Tom Christie

Reputation: 33921

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.

Upvotes: 8

Related Questions