Django序列化器用于一个对象 [英] Django serializer for one object

查看:106
本文介绍了Django序列化器用于一个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找到一种方法,可以将一些Django模型对象序列化为JSON格式,例如:

I'm trying to figure out a way to serialize some Django model object to JSON format, something like:

j = Job.objects.get(pk=1)
##############################################
#a way to get the JSON for that j variable???
##############################################

我不要:

from django.core import serializers
serializers.serialize('json', Job.objects.get(pk=1),ensure_ascii=False)

因为它返回JSON数组,而不是单个对象表示形式.

Because it returns JSON array, not a single object representation.

有什么想法吗?

我正在考虑的一种方法是:找到一种获取对象的哈希值(属性,值),然后使用simplejson来获取其JSON表示形式的方法,但是我不知道如何获取该对象哈希.

One way I'm thinking of: is to find a way to get a hash(attribute,value) of the object and then use simplejson to get the JSON representation of it, however I don't know how to get that hash.

推荐答案

仅按摩您从serializers.serialize中获得的收益如何?从结果的前面和后面修剪方括号并不难.

How about just massaging what you get back from serializers.serialize? It is not that hard to trim off the square brackets from the front and back of the result.

job = Job.objects.get(pk=1)
array_result = serializers.serialize('json', [job], ensure_ascii=False)
just_object_result = array_result[1:-1]

这不是一个很好的答案,但它只会为您提供json表示法中的对象.

Not a fancy answer but it will give you just the object in json notation.

这篇关于Django序列化器用于一个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆