【问题标题】:Django RestFramework returning a precomputed jsonDjango Rest Framework 返回预计算的 json
【发布时间】:2017-05-09 17:25:38
【问题描述】:

目前我有这个:

class MySerializer(serializers.ModelSerializer):

    class Meta:
        model = MyModel
        fields = (
            'id', 'f0', 'f1', 'f2')

它返回如下内容:

{
    "count": 6242,
    "previous": null,
    "total_pages": 209,
    "results": [
        {
            "id": 63915,
            "f0": "Some stuff"
            .....
         },
        {
            "id": 63916,
            "f0": "Some other stuff"
            .....
         }....            

     ]
}

这很好,但我注意到动态序列化数据实际上非常昂贵,所以我想预先计算它。到目前为止,我已经设法预先计算它并将其存储在我的模型的 jsonfield 中,问题是我的 API 现在返回 {'json_repersentation':{myold_response}}

class MySerializer(serializers.ModelSerializer):

    class Meta:
        model = MyModel
        fields = ('json_representation',)

我的问题是,是否可以对其进行更改,使其仅返回包含在 json_representation 字段中的 json 而没有 {'json_representation':{id:0, f0:label...}} 的“开销”,而是只是简单的 {id:0, f0:label...}

【问题讨论】:

    标签: json django django-rest-framework


    【解决方案1】:

    你可以重写序列化器to_representation方法:

    def to_representation(self, instance):
        data = super(MySerializer, self).to_representation(instance)
        return data['json_representation']
    

    【讨论】:

    • 啊!正是我想要的!谢谢。
    猜你喜欢
    • 2019-08-19
    • 1970-01-01
    • 2020-12-30
    • 2023-02-24
    • 1970-01-01
    • 2021-10-02
    • 2013-04-09
    • 2018-03-24
    • 2019-01-05
    相关资源
    最近更新 更多