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',
)
我希望得到creator.username
,因为creator
只返回作为创建者的用户对象的id的整数。我怎样才能获得creator.username而不是creator?
答案 0 :(得分:4)
试试这个。希望creator
字段是只读的,并从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',
)
注意:这会使creator
字段为只读。如果您计划从序列化程序添加它,请为creator.user
名称使用单独的名称。就像下面的例子一样
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',
)
答案 1 :(得分:3)
您可以覆盖序列化方法字段,如下所示,将creator.username
设为creator
,如下所示:
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',
)