4

我有以下型号:

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)

和我可能的序列化器:

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

预期结果:

{
    '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

0 回答 0