Question

I have a Django model (schedule) with the class of entity, that is the parent of Activity, that is the parent of Event.

class Entity(models.Model):
    <...>

class Activity(models.Model):
    <...>
    team_entity = models.ForeignKey(Entity)
    <...>   

class Event(models.Model):
    <...>
    activity = models.ForeignKey(Activity)
    <...>

How do I serialize and get both the child object and grand children as part of the JSON file?

Was it helpful?

Solution 2

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

OTHER TIPS

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/

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.

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.

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.

you can do this in simple two lines of code :

from django.core import serializers
data = serializers.serialize("json", SomeModel.objects.all())
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top