Django: Nesting serializers in each other Django: Nesting serializers in each other json json

Django: Nesting serializers in each other


You have to add a model that contains columns and data attributes because they are currently not linked.

your models.py file :

class Table(models.Model):    passclass Column(models.Model):    data = models.CharField(max_length=200)    title = models.CharField(max_length=200)    table = models.ForeignKey(Table)    def __str__(self):        return self.orderclass Line(models.Model):    doc = models.CharField(max_length=200)    order = models.CharField(max_length=200)    nothing = models.CharField(max_length=200)    table = models.ForeignKey(Table)    def __str__(self):        return self.order

your serializer.py file :

# import your related models and serializersclass ColumnSerializer(serializers.ModelSerializer):    class Meta:        model = Column        fields = [            'data',            'title'        ]class LineSerializer(serializers.ModelSerializer):    class Meta:        model = Line        fields = [            'doc',            'order',            'nothing'        ]class TableSerializer(serializers.ModelSerializer):    columns = ColumnSerializer(many=True)    lines = LineSerializer(many=True)    class Meta:        model = Table        fields = [            'columns',            'lines'        ]

Now use the TableSerializer serializer to serialize and deserialize your Table object.

Concerning your models, Line instead of Data is maybe more appropriate. And

Read Django-Rest-Framework - NestedRelationships for more information and learn how to support write-operations to a nested serializer field.


First you need to modify you models. You can make data ForeignKey field in Column model like:

class Column(models.Model):    data = models.ForeignKey("Data")    title = models.CharField(max_length=200)

Next create a new serializer for Data like:

class DataSerializer(serializers.ModelSerializer):    class Meta:        model = Data

Now you can use DataSerializer in your ColumnSerializer to get data for each column like:

class ColumnSerializer(serializers.ModelSerializer):    data = DataSerializer(read_only=True)    class Meta:        model = Column

This would give output like:

[    {        "title" : "Doc",        "data" :{            "doc": "564251422",            "nothing": 0.0,            "order": "56421"        }     },     {        "title" : "Order no.",        "data" :{            "doc": "546546545",            "nothing": 0.0,            "order": "98745"        }    }]