如何使用多对多关系在Django中反向序列化

时间:2019-03-19 09:27:40

标签: django-rest-framework

我首先制作了类别分类,然后创建了与类别具有多对多关系的产品分类。 models.py(类别)

class Category(models.Model):
    name = models.CharField(max_length=191, blank=False, null=False)
    description = models.TextField(blank=True, null=True)

models.py(产品)

class Product(models.Model):
    product_code = models.CharField(max_length=191, blank=False, null=False)
    name = models.CharField(max_length=191, blank=False, null=False)
    description = models.TextField(blank=False, null=False)
    price = models.DecimalField(max_digits=19, decimal_places=2)
    photo = models.ImageField(upload_to='pictures/products/', max_length=255, null=False, blank=False)
    category = models.name = models.ManyToManyField(Category)

如何获得以下结果。

  {
        "categories": [
            {
                "id": 1,
                "name": "Indoor Muscle Training",
                "description": null,
                "products":{
                       "name":"product_name",
                       "code":"product_code"
                }
            },
            {
                "id": 2,
                "name": "Outdoor Muscle Training",
                "description": null,
                "products":{
                       "name":"product_name",
                       "code":"product_code"
                }
            }
        ]
    }

1 个答案:

答案 0 :(得分:1)

在这种情况下,可以使用

使用serializer-method字段。我们的目标是从product序列化程序中获取category信息。所以为此

class CategorySerializer(serializers.ModelSerializer):
    products = serializers.SerializerMethodField()

    class Meta:
        model = Category
        fields = ('') # add relative fields

   def get_products(self, obj):
       products = obj.product_set.all() # will return product query set associate with this category
       response = ProductSerializer(products, many=True).data
       return response