serializers.py
from django.contrib.auth.models import User
from engine.models import Game
from rest_framework import serializers
class GameSerializer(serializers.ModelSerializer):
    class Meta:
        model = Game
        fields = (
            'game_name',
            'level',
            'game_type',
            'creator',
            'id',
        )
I want to get creator.username as creator just returns the integer of the id of the user object that is the creator. How can I get creator.username instead of creator?
Try this. Hope the creator field is read only and is assigned from the view like request.user
from django.contrib.auth.models import User
from engine.models import Game
from rest_framework import serializers
class GameSerializer(serializers.ModelSerializer):
    creator = serializers.CharField(read_only=True, source='creator.username')
    class Meta:
        model = Game
        fields = (
            'game_name',
            'level',
            'game_type',
            'creator',
            'id',
        )
Note :  This will make the creator field read only. If you are planning to add it from the serializer, then use separate name for the creator.user name. Just like the following example
class GameSerializer(serializers.ModelSerializer):
    creator_name = serializers.CharField(read_only=True, source='creator.username')
    class Meta:
        model = Game
        fields = (
            'game_name',
            'level',
            'game_type',
            'creator',
            'creator_name',
            'id',
        )
                        You can override serializer method field as below to get creator.username as creator as follow:
class GameSerializer(serializers.ModelSerializer):
    creator = serializers.SerializerMethodField(read_only=True)
    def get_creator(self, obj):
        # obj is model instance
        return obj.creator.username
    class Meta:
        model = Game
        fields = (
            'game_name',
            'level',
            'game_type',
            'creator',
            'id',
        )
                        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