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