6

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 posible 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')

The 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}
    ]
}
olanod
  • 30,306
  • 7
  • 46
  • 75
  • 2
    Is this the answer to your question? http://stackoverflow.com/questions/17256724/include-intermediary-through-model-in-responses-in-django-rest-framework – WSV Nov 26 '13 at 23:04
  • take a dict and manually give key as 'name' and 'packing' and update it with list of packing – Amrit Jan 09 '17 at 12:27

0 Answers0