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?
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.
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.
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.
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/
I now use django-piston. This does the trick.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With