Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serializing Many To Many intermediate table in Django Rest Framework

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:

  1. First problem is it duplicates data because of many to many table
  2. I want to see my product and material 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.

like image 824
adnan kaya Avatar asked Sep 12 '18 12:09

adnan kaya


Video Answer


1 Answers

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
like image 79
JPG Avatar answered Nov 02 '22 20:11

JPG