简体   繁体   中英

Serialize django model with foreign key models

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

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

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 !

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

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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