gpt4 book ai didi

django - 获取序列化器中字段的属性(django rest 框架)

转载 作者:行者123 更新时间:2023-12-03 18:37:42 24 4
gpt4 key购买 nike

序列化程序.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?

最佳答案

您可以按如下方式覆盖序列化程序方法字段以获得 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',
)

关于django - 获取序列化器中字段的属性(django rest 框架),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49663829/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com