django model serialization
I want to serialize models so:
class Schedule(models.Model):
Title = models.CharField(max_length=512)
class ScheduleEvent1(models.Model):
ScheduleContent = models.ForeignKey(Schedule)
Description = models.TextField()
class ScheduleEvent2(models.Model):
ScheduleContent = models.ForeignKey(Schedule)
AnotherField = models.TextField()
ShortDescription = models.TextField()
make smth like serializers.serialize('json', Schedule.objects.all())
The result likes
[
{
"pk": 2,
"model": "Schedule",
"fields": {
"Title": "Some Title",
"Schedul开发者_如何学PythoneEvent1": [
{
"pk": 19,
"model": "ScheduleEvent1",
"fields": {
"Description": "Some Descr",
}
},
{
"pk": 20,
"model": "ScheduleEvent1",
"fields": {
"Description": "Some Descr2222",
}
}
],
"ScheduleEvent2": [
{
"pk": 15,
"model": "ScheduleEvent2",
"fields": {
"AnotherField": "Some text",
"ShortDescription" : "Some text ...",
}
}
]
}
}
]
In general. I have entity tree. And I need serialize this tree from root.
tnx for help.
http://docs.djangoproject.com/en/1.3/topics/serialization/#dependencies-during-serialization
Covers the essence of this. The resulting file is not precisely what's required, since the objects won't be nested. However it is what Django produces by default and it's what Django will use for deserialization.
If you use Piston you can easily define a Handler which will produce nested JSON, but it won't be precisely as shown because Piston's JSON emitter isn't precisely in the Django format.
Getting to precisely what's hoped-for leads to extending the Django serializer to produce a nested JSON object as the natural key. See http://code.djangoproject.com/browser/django/trunk/django/core/serializers/python.py. Lines 47-59
Or, you can define a natural_key
method which uses Django's 'django.core.serializers.json .Serializer` to emit the JSON serialization of the object instead of some other natural key value. This is a little weird semantically, but it may do what you want.
精彩评论