我想学习如何整体获取多对多中间表的序列化程序数据 model
,不仅仅是通过 id。
#this is my model class
class ProductMaterial(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
material = models.ForeignKey(Material, on_delete=models.CASCADE)
material_rate = models.FloatField(blank=True, null=True)
material_price = models.FloatField(blank=True, null=True)
#serializer
class ProductMaterialSerializer(serializers.ModelSerializer):
class Meta:
model = ProductMaterial
fields = '__all__'
这将返回:
{
"id": 1,
"material_rate": 0.3,
"material_price": 6.7,
"product": 186,
"material": 7
},
{
"id": 2,
"material_rate": 0.7,
"material_price": 1.7,
"product": 186,
"material": 8
},
问题:
product
和 material
模型字段也是。 我的目标:
{
"id": 1,
"product": {
"name" : "abcd",
"date" : "01.01.2018"
},
"material": [
{
"id" : 7,
"material_rate" : 0.3,
"material_price" : 6.7,
},
{
"id" : 8,
"material_rate" : 0.7,
"material_price" : 1.7,
},
]
},
解决方案2:
我已经实现了这个解决方案 -> https://stackoverflow.com/a/45834689/5491260
它帮助了我。
最佳答案
从文档中,
The depth option should be set to an integer value that indicates the depth of relationships that should be traversed before reverting to a flat representation.
所以,使用
depth=1
在元类中class ProductMaterialSerializer(serializers.ModelSerializer):
class Meta:
model = ProductMaterial
fields = '__all__'
depth = 1
关于django - 在 Django Rest Framework 中序列化多对多中间表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52295480/