python - Django serialization get foreign key object with primary key object -


i need serialize django model instance foreign keys instance. ex.

class person(models.model):     first_name = models.charfield(max_length='30')     last_name = models.charfield(max_length='30')  class author(models.model):     reg_num = models.charfield(max_length = '30')     person = models.foreignkey(person) 

so in serialized version of authon instance, want like

[     {         "fields":         {             "reg_num": "czg29742xd4",             "person":              {                 "fields":                 {                     "first_name": "dheerendra",                     "last_name": "rathor"                 }                 "model": "person.person",                 "pk": 2             }        }        "model": "person.author",        "pk": 2     } ] 

this can achieved providing both person , author objects serializers.

enter image description here

enter image description here

in [39]: person.models import *  in [40]: django.core import serializers  in [41]: query_obj = author.objects.get(person__first_name = 'dheerendra')  in [42]: ser_json = serializers.serialize('json', [query_obj, query_obj.person])  in [43]: ser_json out[43]: '[{"pk": 1, "model": "person.author", "fields": {"reg_num": "czg29742xd4", "person": 1}}, {"pk": 1, "model": "person.person", "fields": {"first_name": "dheerendra", "last_name": "rathor"}}]'  in [45]: ast import literal_eval   in [46]: ser_json = literal_eval(ser_json)  in [47]: ser_json[0]['fields']["person"] = ser_json[1]  in [48]: [ser_json[0]] out[48]:  [   {            'fields':            {             'reg_num': 'czg29742xd4',             'person':              {               'fields':                      {                           'first_name': 'dheerendra',                           'last_name': 'rathor'                     },                     'model': 'person.person',                     'pk': 1            }       }   'model': 'person.author',   'pk': 1   } ] 

you can convert json object using simplejson library.

in [1]: import simplejson  in [2]: ser_json = simplejson.dumps([ser_json[0]]) 

Comments

Popular posts from this blog

matlab - "Contour not rendered for non-finite ZData" -

delphi - Indy UDP Read Contents of Adata -

javascript - Any ideas when Firefox is likely to implement lengthAdjust and textLength? -