让Django在没有“字段"的情况下序列化对象场地 [英] Getting Django to serialize objects without the "fields" field
问题描述
因此,我正在使用Django编写后端Web服务来创建&使用JSON,而我的同事正在研究ExtJS4前端.我正在使用wadofstuff序列化程序,以便可以序列化嵌套对象.
So I am working on writing the backend web service using Django to create & consume JSON, and my colleague is working on the ExtJS4 frontend. I'm using the wadofstuff serializer so I can serialize nested objects.
我的同事在解析json时遇到问题,特别是Django将对象的字段放在字段"字段中.一个简短的例子:
My colleague is having trouble parsing the json, specifically that Django puts the fields for an object inside a "fields" field. A short example:
现在事物序列化的方式:
The way things are being serialized now:
{
"pk":1,
"model":"events.phone",
"fields":{
"person":1,
"name":"Cell",
"number":"444-555-6666"
}
}
我想序列化它们以使ExtJS和我的开发人员感到高兴的方式:
The way I would like to serialize them to make ExtJS and my fellow developer happy:
{
"pk":1,
"model":"events.phone",
"person":1,
"name":"Cell",
"number":"444-555-6666"
}
我们将需要序列化一些比这复杂得多的对象.
We will need to serialze some objects that are much more complicated than this however.
有什么办法可以手动编写序列化序列,以使Django或wadofstuff序列化序列不使用fields字段?
Is there any way short of writing my serializations by hand to make the Django or wadofstuff serializer not use a fields field?
推荐答案
自定义序列化的最佳方法是让Django首先序列化为Python字典.然后,您可以对自己喜欢的那些字典进行后处理,然后再将它们转储到JSON中:
The best way to customize your serialization is to get Django to serialize to Python dicts first. Then you can post-process those dicts however you like, before dumping them out to JSON:
# this gives you a list of dicts
raw_data = serializers.serialize('python', Phone.objects.all())
# now extract the inner `fields` dicts
actual_data = [d['fields'] for d in raw_data]
# and now dump to JSON
output = json.dumps(actual_data)
这篇关于让Django在没有“字段"的情况下序列化对象场地的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!