【发布时间】:2021-01-30 05:02:16
【问题描述】:
我是 Python 和 Django Rest 框架的新手。我正在尝试返回“自定义”json 响应,但我不知道如何实现我想要的结果。
我正在构建一个电子商务 api,其中我有带有“产品”的“盒子”,创建这个 BoxProduct 模型是因为我需要产品和盒子之间的关系,但是相同的产品可以在不同的盒子中,例如:产品。 id=1 在 box_id=2 和 box_id=4 中。这就是我创建这个中间模型的原因。
盒子产品模型
class BoxProduct(models.Model):
product = models.ForeignKey(Product, on_delete=models.DO_NOTHING, null=True, related_name='box_product')
box = models.ForeignKey(Box, on_delete=models.DO_NOTHING, null=True, related_name='box_box')
product_price = models.DecimalField(max_digits=8, decimal_places=0, null=True, blank=True)
我尝试链接 Product 和 Box 的序列化程序,但没有得到我想要的。
BoxProduct 序列化程序
class BoxProductSerializer(serializers.ModelSerializer):
product = ProductSerializer(many=True, read_only=True)
box = BoxSerializer()
class Meta:
model = BoxProduct
fields=['box', 'product']
这个想法是有一个像这样返回的 json:
{
"box_id": 232323,
"box_name": "Box name Test",
"products": [
{
"name": "product name 1",
"type": "product_type"
},
{
"name": "product name 2",
"type": "product_type"
},
{
"name": "product name 3",
"type": "product_type"
}
]
}
最好的方法是什么?
感谢您的帮助!
【问题讨论】:
-
您在
BoxProduct中指定product_price,而不是在Product中。这是否意味着不同盒子的产品价格可能不同? -
是的!装在盒子里的产品会有不同的价格。
标签: python json django django-rest-framework