我想学习如何通过整个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,
},
]
},
我已经实现了此解决方案-> https://stackoverflow.com/a/45834689/5491260 它帮助了我。
答案 0 :(得分:2)
从文档中
depth选项应设置为整数值,以指示 在恢复到关系之前应遍历的关系深度 平面表示法。
因此,请在Meta类中使用depth=1
class ProductMaterialSerializer(serializers.ModelSerializer):
class Meta:
model = ProductMaterial
fields = '__all__'
depth = 1