Reputation: 579
I would like to learn how to get many to many intermediate table's serializer data by whole model
, not only by id.
#this is my model class
class ProductMaterial(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
material = models.ForeignKey(Material, on_delete=models.CASCADE)
material_rate = models.FloatField(blank=True, null=True)
material_price = models.FloatField(blank=True, null=True)
#serializer
class ProductMaterialSerializer(serializers.ModelSerializer):
class Meta:
model = ProductMaterial
fields = '__all__'
This returns:
{
"id": 1,
"material_rate": 0.3,
"material_price": 6.7,
"product": 186,
"material": 7
},
{
"id": 2,
"material_rate": 0.7,
"material_price": 1.7,
"product": 186,
"material": 8
},
product
and material
model fields too.{
"id": 1,
"product": {
"name" : "abcd",
"date" : "01.01.2018"
},
"material": [
{
"id" : 7,
"material_rate" : 0.3,
"material_price" : 6.7,
},
{
"id" : 8,
"material_rate" : 0.7,
"material_price" : 1.7,
},
]
},
I have implemented this solution -> https://stackoverflow.com/a/45834689/5491260 and it helped me.
Upvotes: 8
Views: 4245
Reputation: 88459
From the doc,
The depth option should be set to an integer value that indicates the depth of relationships that should be traversed before reverting to a flat representation.
So, use depth=1
in Meta class
class ProductMaterialSerializer(serializers.ModelSerializer):
class Meta:
model = ProductMaterial
fields = '__all__'
depth = 1
Upvotes: 5