Django serialize to JSON

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?

By : Steven H.


Answers

you can do this in simple two lines of code :

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


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.

By : gsiegman


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

By : Steven H.


This video can help you solving your question :)
By: admin