用外键模型序列化Django模型 [英] Serialize django model with foreign key models

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

问题描述

如果要包含外键模型字段,如何以json格式序列化Django模型?

How to serialize Django model in json format if I want to include foreign key models fields?

如果我有:

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

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

我想将所有内容都包含在json ...

I wanna include everything in json...

推荐答案

我遇到了类似的问题所以我采用了以前做过的一些代码,并对其进行了改进。实际上,它最终出现在完整的python序列化框架SpitEat中。您可以在此处下载试用版。该文档还不是很好,所以这里是您用来序列化事物的代码:

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. 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 !

当然,一旦序列化了对象,只需使用 json 作为:

Of course, once your have your object serialized, just use json as :

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

然后您就来了!

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

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