首页 > 解决方案 > 如何在返回的 JSON 中仅呈现模型的属性?

问题描述

我正在使用 Python 3.7 和 Django。我有一个返回以下内容的视图

# Ajax request that returns articles with similar words in the titles
def get_hints(request):
    ...
    s = ArticlesService()
    objects = s.get_hints(article)
    data = serializers.serialize('json', objects)
    return HttpResponse(data, content_type="application/json")

“get_hints”方法返回一个模型对象数组。问题是,在 Javascript 方面,JSON 是这样返回的......

[{model: "mydb.article", pk: 60945, fields: { title: "Cooking Eggplant", path: "https://thecookingblog.com/abcde", label: "" },
    ...]

有没有办法在没有“模型”和“字段”的情况下返回 JSON,而只是将对象的属性作为更传统的 JSON 返回,例如

{ title: "Cooking Eggplant", path: "https://thecookingblog.com/abcde", label: "" }

?

标签: pythonjsondjangopython-3.xview

解决方案


是的。类的get_dump_object方法Serializer负责以下格式

{
    "pk": "pk_val",
    "model": "model_name",
    "fields": {
        "model_field": "model_field_value",
        ...
    }
}

以下是该get_dump_object方法的当前实现。

def get_dump_object(self, obj):
    data = OrderedDict([('model', str(obj._meta))])
    if not self.use_natural_primary_keys or not hasattr(obj, 'natural_key'):
        data["pk"] = self._value_from_field(obj, obj._meta.pk)
    data['fields'] = self._current
    return data

由于您不需要pkandmodel字段,因此您可以创建自己的序列化程序类并覆盖get_dump_object方法。

from django.core.serializers.json import Serializer as JSONSerializer

class MyCustomSerializer(JSONSerializer):
    def get_dump_object(self, obj):
        return self._current

然后就可以得到如下格式的数据

[{ title: "Cooking Eggplant", path: "https://thecookingblog.com/abcde", label: "" }, ....]

通过调用它的serialize方法。

data = MyCustomSerializer().serialize(objects)
return HttpResponse(data, content_type="application/json")

推荐阅读