我试图弄清楚如何设置嵌套的序列化程序。
# models.py
class Product(models.Model):
sku = models.CharField()
product_name = models.CharField()
class Order(models.Model):
name = models.CharField()
address = models.CharField()
class OrderProduct(models.Model):
order = models.ForeignKey( Order )
product = models.ForeignKey( Product )
quantity = models.IntegerField()
所以我想拥有一个可以创建以下形式的订单的api:
{
"name" : "James",
"address" : "100 Main St",
"products" : [
{ "sku" : "1234", "quantity" : 1 }
]
}
我了解到我需要在OrderSerializer内嵌套OrderProductSerializer,但是当“产品”数据使用OrderProduct模型中未找到的字段“ sku”时,如何在此处实现它。我要进行双重嵌套吗?看起来如何?
# serializers.py
class OrderProductSerializer( serializers.ModelSerializer):
class Meta:
model = OrderProduct
exclude = ()
class OrderSerializer(serializers.ModelSerializer):
products = OrderProductsSerializer(many=True)
class Meta:
model = Order
exclude = ()
答案 0 :(得分:1)
您正试图在反向关系上实现嵌套序列化。因此,您必须通过source
参数将关系名称作为参数显式提供给序列化程序。
试试这个
class OrderProductSerializer(serializers.ModelSerializer):
class Meta:
model = OrderProduct
fields = '__all__'
class OrderSerializer(serializers.ModelSerializer):
product = OrderProductSerializer(many=True, source='product_set')
class Meta:
model = Order
fields = '__all__'
有关更多信息,请参考以下文档
1. DRF Nested Relationship
2. DRF-Reverse Realation
3. What is reverse-relationship
in Django