Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
126 views
in Technique[技术] by (71.8m points)

python - Django serializer for one object

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???
##############################################

I don't want:

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

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

Any ideas?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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]

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...