tags:

views:

34

answers:

2

How to serialize dajngo model in json format if i want 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....

A: 

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)
singularity
But i need to do it with filter... And its looks like i need to do the same but in loop.. I suppose that there have to be more easy way...
Pol
+1  A: 

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

sebpiq