显示相关字段属性

时间:2016-09-29 06:52:13

标签: django django-rest-framework

我该怎么做才能显示ForeignKey protected_area的名字字段?:

class NotificationReceiverSerializer(serializers.ModelSerializer):
    class Meta:
        model = NotificationReceiver
        fields = ('pk','cellphone', 'protected_area__name')

所以现在它正如预期的那样显示为PK:

protected_area":1

1 个答案:

答案 0 :(得分:2)

尝试这样的事情。

class NotificationReceiverSerializer(serializers.ModelSerializer):
    proteced_area = serializers.ReadOnlyField(source="protected_area.name")

    class Meta:
        model = NotificationReceiver
        fields = ('pk','cellphone', 'protected_area')

这会将protected_area名称显示为只读字段。或者,

class NotificationReceiverSerializer(serializers.ModelSerializer):
    proteced_area = ProtectedAreaSerializer(read_only=True, many=True)

    class Meta:
        model = NotificationReceiver
        fields = ('pk','cellphone', 'protected_area')

显示相关模型中的所有字段