我首先制作了类别分类,然后创建了与类别具有多对多关系的产品分类。 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"
}
}
]
}
答案 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