Serializing a django model with foreign keys

How to serialize a Django model in json format if I want to include foreign key model 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 want to include everything in json ...

+3
source share
2 answers

I had similar problems, so I took the code I was doing before and improved it. It actually ended in a full-fledged python SpitEat serialization platform. You can download it here . The documentation is not very good yet, so here is the code you should use to serialize your stuff:

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

, , . (, ..) ). , , , , !

, , json :

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

, !

+2

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)
+1

All Articles