Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting attribute of field in serializer (django rest framework)

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?

like image 222
Michael Avatar asked Dec 10 '22 07:12

Michael


2 Answers

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',
        )
like image 144
Aneesh R S Avatar answered Mar 08 '23 01:03

Aneesh R S


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',
        )
like image 30
Gahan Avatar answered Mar 08 '23 01:03

Gahan