Serialize M2M Relationship Using Table

I have the following models:

class Packing(models.Model): name = models.CharField(max_length=100) size = models.CharField(max_length=50,blank=True) class Product(models.Model): name = models.CharField(max_length=100) packing = models.ManyToManyField(Packing,related_name='products',through='Presentation') class Presentation(models.Model): product = models.ForeignKey(Product) packing = models.ForeignKey(Packing) weight = models.DecimalField(decimal_places=3,max_digits=10) price = models.DecimalField(decimal_places=2,max_digits=10) 

and my possible serializer:

 class PresentationSerializer(serializers.ModelSerializer): class Meta: model = Presentation class ProductSerializer(serializers.ModelSerializer): packing = PresentationSerializer(many=True,read_only=True,) class Meta: model = Product fields = ('name','packing') 

Expected Result:

 { 'name': 'produt', 'packing': [ {'name':'abcd','size':'big','weight':200,'price':222.22}, {'name':'qwert','size':'small','weight':123,'price':534.21}, {'name':'foo','size':'xxx','weight':999,'price':999.99} ] } 
+4
source share

Source: https://habr.com/ru/post/1484832/


All Articles