0
在Android客戶端,我做出一個服務器端點的請求與ContactRequest
身體:如何在DRF服務器端訪問請求體模型字段?
public class ContactRequest {
@SerializedName("senderId")
@Expose
private int senderId;
@SerializedName("receiverId")
@Expose
private int receiverId;
public ContactRequest(int senderId, int receiverId) {
this.senderId = senderId;
this.receiverId = receiverId;
}
}
使用改裝我通過這個對象作爲請求體:
@POST("friendship/create-friend-request/")
Call<Void> sendRequest(@Body ContactRequest contactRequest);
在服務器當該請求被這個端點作出
class CreateFriendRequestView(views.APIView):
def post(self, request, *args, **kwargs):
sender = User.objects.get(pk=request.senderId)
receiver = User.objects.get(pk=request.receiverId)
Friend.objects.add_friend(sender, receiver)
return Response({'status': 'Request sent'}, status=201)
然而:側,我然後映射這個端點到CreateFriendRequestView
當調用該視圖時,發生內部服務器錯誤,狀態碼500。
AttributeError: 'Request' object has no attribute 'senderId'
我怎樣可以參考的字段,在Django的REST框架客戶端senderId
和receiverId
?
謝謝,或者它可以使用訪問:request.data ['senderId'] –
是的,你是正確的。只要'get'方法允許你給出一個默認值,以防給定的鍵在字典中不存在。例如:'request.data.get('senderId',1)' –