Django序列化器字段不起作用

时间:2018-04-29 00:58:14

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

虽然我查看了提出的问题,但我找不到解决方案......

当我使用这个序列化器时:

class MessageSerializer(ModelSerializer):
    sender = UserMobileSerializer(read_only=True)

    class Meta:
        model = Messages
        fields = '__all__'

我得到这样的东西:

{
    "id": 62,
    "sender": {
        "pk": 12,
        "email": "john@gmail.com",
        "full_name": "John",
        "profile_photo": null
    },
    "created_at": "2018-04-29T00:54:50.437662",
    "message": "sdkjnasljdhkajsjdlasdasda",
    "read_at": false,
    "target": 18
}

我希望target字段与sender类似,即:显示完整的用户信息,而不仅仅是ID。

我尝试添加此行:target = UserMobileSerializer(),但我仍然只获得输出中的ID。我也试过target = UserMobileSerializer(read_only=True)但没有改变。

1 个答案:

答案 0 :(得分:0)

您没有将您定义的字段添加到序列化程序fields中的Meta。试试这个:

class MessageSerializer(ModelSerializer):
    sender = UserMobileSerializer(read_only=True)

    class Meta:
        model = Messages
        fields = ('your', 'fields', 'sender')

编辑:您也需要序列化target。像这样:

class TargetSerializer(ModelSerializer):
    class Meta:
        model = Target
        fields = ('id', 'title')  # Add fields you want to get in the response.


class MessageSerializer(ModelSerializer):
    target = TargetSerializer(read_only=True)  # You should have TargetSerializer defined
    sender = UserMobileSerializer(read_only=True)

    class Meta:
        model = Messages
        fields = ('your', 'fields', 'target', 'sender')