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
},
Problems:
- First problem is it duplicates data because of many to many table
- I want to see my
product
andmaterial
model fields too.
My target:
{
"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,
},
]
},
Solution 2:
I have implemented this solution -> https://stackoverflow.com/a/45834689/5491260 and it helped me.