Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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 !

Solution 2:

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)

Post a Comment for "Serialize Django Model With Foreign Key Models"