I'm figuring out how serializers can be merged or nested into each other. In this example I have a column model (consisting of Column
class) and data that belong to the column model (consisting of Data class
). My problems is that I don't know how to call ModelSerializer from another serializer class and pass the arguments (the result is always empty).
Can you advice me if my model is correct for this situation and how to create the desired JSON so that the result reuses existing serializers and avoids duplicating any data?
Note: in best case the data attributes should be dependent on each other, so that only those data get serialized that are defined as columns.
models.py
class Column(models.Model):
data = models.CharField(max_length=200)
title = models.CharField(max_length=200)
def __str__(self):
return self.order
class Data(models.Model):
doc = models.CharField(max_length=200)
order = models.CharField(max_length=200)
nothing = models.CharField(max_length=200)
def __str__(self):
return self.order
Desired output:
{
"columns": [
{
"data": "doc",
"title": "Doc."
},
{
"data": "order",
"title": "Order no."
},
{
"data": "nothing",
"title": "Nothing"
}
],
"data": [
{
"doc": "564251422",
"nothing": 0.0,
"order": "56421"
},
{
"doc": "546546545",
"nothing": 0.0,
"order": "98745"
}
]
}
But the result with ModelSerializer is like this:
[
{
"doc": "564251422",
"order": "56421",
"nothing": "0.0"
},
{
"doc": "546546545",
"order": "98745",
"nothing": "0.0"
}
]