Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django serialize to JSON

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?

like image 900
Steven H. Avatar asked Jan 05 '09 21:01

Steven H.


People also ask

What is serialize in Django?

Serializers in Django REST Framework are responsible for converting objects into data types understandable by javascript and front-end frameworks. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.

How do I serialize Queryset?

To serialize a queryset or list of objects instead of a single object instance, you should pass the many=True flag when instantiating the serializer. You can then pass a queryset or list of objects to be serialized.

What is To_representation Django?

to_representation(self, value) method. This method takes the target of the field as the value argument, and should return the representation that should be used to serialize the target. The value argument will typically be a model instance.


2 Answers

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/

like image 114
Sergey Golovchenko Avatar answered Oct 03 '22 10:10

Sergey Golovchenko


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

like image 24
Steven H. Avatar answered Oct 03 '22 12:10

Steven H.