![](/img/trans.png)
[英]How can I convert my json response to nested json where attributes are under another 'attribute'?
[英]How can I render only the attributes of my model in returned 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返回而没有“ model”和“ fields”,而只是将对象的属性作为更传统的JSON返回,例如
{ title: "Cooking Eggplant", path: "https://thecookingblog.com/abcde", label: "" }
?
是。 Serializer
类的get_dump_object
方法负责以下格式
{
"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
由于您不需要pk
和model
字段,因此可以创建自己的serialzer类并重写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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.