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

时间:2018-04-05 03:46:44

标签: django django-rest-framework django-serializer

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?

2 个答案:

答案 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',
        )