1👍
This can be achieved by providing both person
and author
objects to serializers
.
In [39]: from person.models import *
In [40]: from 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]: from 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 it back to json
object using simplejson
library.
In [1]: import simplejson
In [2]: ser_json = simplejson.dumps([ser_json[0]])
0👍
0👍
Django doesn’t support this in-depth serialization
https://code.djangoproject.com/ticket/4656
You can use django rest framework or tastypie to do that. Both are well capable to do that.
- [Answer]-Required and Optional Field in Django Formset
- [Answer]-Django model add data to model only if boolean field is true
- [Answer]-Django redirect with full url and primary key in template
Source:stackexchange.com