如何从序列化器中将一个字段显示为字符串?

时间:2016-12-09 19:11:34

标签: python django rest serialization

我使用rest框架,我在用户emloyee.company中有字段,该字段具有字段名称。我只需要显示名称字符串,但我有dict。

class CompanySerializer(serializers.ModelSerializer):
    class Meta:
        model = Company
        fields = ('name',)


class UserSerializer(MySerializer):
    company = CompanySerializer(source='employee.company')

    class Meta:
        fields = (..., 'company')

我有:

{...,"company":{"name":"My company"}}

我需要:

{...,"company":"My company"}

感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

变化:

company = CompanySerializer(source='employee.company')

为:

company = serializers.ReadOnlyField(source='employee.company.name')