根据 Serializing Django objects | Django documentation | Django ,使用内置默认的 serializer 格式化的 JSON 如下:

[
    {
        "pk": "4b678b301dfd8a4e0dad910de3ae245b",
        "model": "sessions.session",
        "fields": {
            "expire_date": "2013-01-16T08:16:59.844Z",
            ...
        }
    }
]

里面带有 pk, model 等我们不想要的属性,或者我们想添加一些自定义属性,该如何处理。

解决方法

Google 了一大圈,没发现有自己想要的方案。其实想法很简单,获取到原始数据进行二次封装处理即可,并不需要继承实现自己的 Serializer

class JSONResponse(HttpResponse):
    """
    An HttpResponse that renders its content into JSON.
    """
    def __init__(self, data, fields, **kwargs):
        content = serializers.serialize('json', data, fields=fields)
        obj = json.loads(content)

        content = [instance['fields'] for instance in obj]
        response_data = {}
        response_data['totalPages'] = 1
        response_data['currentPage'] = 1
        response_data['result'] = content

        kwargs['content_type'] = 'application/json'
        super(JSONResponse, self).__init__(json.dumps(response_data), **kwargs)

def index(request):
    list = Restaurant.objects.all()
    return JSONResponse(list)