作为Django REST Framework的新手,我在ModelSerializer中给出了主键的反序列化问题。 例如,我有2个扩展ModelSerializer的序列化器:
class CourierSerializer(serializers.ModelSerializer):
class Meta:
model = Courier
fields = (
"first_name",
"last_name",
"phone"
)
class OrderSerializer(serializers.ModelSerializer):
courier = CourierSerializer()
class Meta:
model = Order
fields = (
"number",
"courier"
)
我的基于类的视图如下所示:
class OrderList(generics.ListCreateAPIView):
model = Order
serializer_class = OrderSerializer
现在,当我将Order模型序列化为JSON时,我得到了我想要的东西 - 对象“Order”,其中包含有关它的“Courier”的详细嵌套信息:
[
{
id: 1,
number: "000231",
courier: {
id: 2,
first_name: "John",
last_name: "Smith",
phone: "12345678"
}
},
...
]
但是在客户端的POST调用中,我想只接收Courier的外键:
{
id: 1,
number: "000231",
courier: 2
}
我应该在OrderSerializer类中添加什么来将这种JSON反序列化为Order模型?我应该写restore_object()吗?或者我应该编写额外的序列化程序来反序列化?如何使用我的(generics.ListCreateAPIView)视图,我可以使用两个单独的序列化器(一个用于列表,一个用于帖子)用于此目的吗?
答案 0 :(得分:4)
您可以向Courier添加带主键的其他序列化程序:
class OrderSerializerForPost(serializers.ModelSerializer):
courier = serializers.PrimaryKeyRelatedField()
class Meta:
model = Order
fields = (
"number",
"courier"
)
然后用你的压倒性的帖子mehtod ...
class OrderList(generics.ListCreateAPIView):
model = Order
serializer_class = OrderSerializer
def post(self, request):
self.serializer_class = OrderSerializerForPost
super(OrderList, self).post(request)
或者您可以尝试重新定义get_serializer_class方法:
class OrderList(generics.ListCreateAPIView):
model = Order
serializer_class = OrderSerializer
def get_serializer_class(self):
if self.request.method == 'GET':
return self.serializer_class
elif self.request.method == 'POST':
return OrderSerializerForPost