[Fixed]-Django serialize to JSON

7👍

I now use django-piston. This does the trick.

10👍

Before you do serialization, when retrieving your objects, to preserve the relationships use select_related() to get children, grandchildren, etc

see http://docs.djangoproject.com/en/dev/ref/models/querysets/

5👍

It seems to me that the question the poster was asking was to end up with a result like:

For instance, starting with these models:

class Entity(models.Model):
    name = models.CharField(...)

class Activity(models.Model):
    name = models.CharField(...)
    team_entity = models.ForeignKey(Entity)

class Event(models.Model):
    name = models.CharField(...)
    activity = models.ForeignKey(Activity)

Result in JSON:

{
    "model": "Entity",
    "name":  "Dallas Cowboys",
    "activities": [
        {
            "model": "Activity",
            "name": "Practice"
        },

        {
            "model": "Activity",
            "name": "Game"
            "events": [
                {
                    "model": "Event",
                    "name": "vs Washington Redskins"
                },

                {
                    "model": "Event",
                    "name": "vs Green Bay Packers"
                }
            ]
        }
    ]
}

Thus keeping the parent-child-grandchild (not inheritence, but one-to-many relationship traversal). If this wasn’t the initial poster’s intention, I apologize…but if so I would like the answer to this as well.

3👍

Have a look at serializing inherited models and objects from the Django documentation available at http://docs.djangoproject.com/en/dev/topics/serialization/?from=olddocs#inherited-models

That should solve your problem.

👤Sarat

3👍

I believe you can find your answer here: http://code.djangoproject.com/ticket/4656

This will become part of django serializers at some stage. Right now it should be able to just replace standard django serializers with this and work away.

-1👍

you can do this in simple two lines of code :

from django.core import serializers
data = serializers.serialize("json", SomeModel.objects.all())

Leave a comment