简体   繁体   English

使用外键模型序列化django模型

[英]Serialize django model with foreign key models

How to serialize Django model in json format if I want to include foreign key models fields? 如果我想包含外键模型字段,如何以json格式序列化Django模型?

If I have: 如果我有:

class Model1(models.Model):
    name=models.CharField()
    child=models.ForeignKey(Model2)

class Mode2(models.Model):
    field1=models.CharField()
    field2=models.IntegerField()

I wanna include everything in json... 我想把所有东西都包括在json里......

I had similar problems so I took some code that I had done before, and improved it. 我有类似的问题,所以我采取了一些我以前做过的代码,并对其进行了改进。 It actually ended-up in a full python serialization framework SpitEat. 它实际上是在一个完整的python序列化框架SpitEat中结束的。 You can download an try it here . 你可以在这里下载试试吧。 The documentation is not very good yet, so here is the code you have to use to serialize your thing : 文档还不是很好,所以这里是你必须用来序列化你的东西的代码:

>>> from spiteat.djangosrz import DjangoModelSrz #you should actually put spiteat in your path first
>>> Model1Srz = DjangoModelSrz.factory(Model1)
>>> srz_instance = Model1Srz(some_obj_you_want_to_serialize)
>>> srz_instance.spit()
... {
...    'pk': <a_pk>,
...    'id': <an_id>,
...    'name': <a_name>,
...    'child': {
...        'pk': <another_pk>,
...        'id': <another_id>,
...        'field1': <a_value>,
...        'field2': <another_value>
...    }
... }

So, complete, deep serialization. 所以,完整,深入的序列化。 You can customize things (choose which fields are included, etc ... But that's not tested yet, and not well documented). 您可以自定义事物(选择包含哪些字段等等......但是尚未测试,并且没有详细记录)。 The doc will become better in the next days, as the code will, so you can begin to use it without fearing that there will be no support ! 随着代码的存在,文档将在接下来的几天内变得更好,因此您可以开始使用它,而不必担心没有支持!

Of course, once your have your object serialized, just use json as : 当然,一旦你的对象被序列化,只需使用json

>>> import json
>>> json_srz = json.dumps(srz_instance.spit())

And you have what you came for ! 你有你想要的!

it's been sometimes that i didn't work on django but is this work for you ? 有时我不会在django上工作,但这对你有用吗?

import simplejson as json

data = Model1.objects.get(pk=some_id)

to_dump =  {'pk': data.pk, 'name':data.name, 
           'fields':{'field_1':data.child.field_1, 
                     'field_2':data.child.field_2 
                    }
            }

json_data = json.dumps(to_dump)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM