2017-07-27 66 views
2

我正在爲我的android應用程序構建一個drf後端api。我需要該API能夠將朋友請求從用戶發送給相關用戶。爲此,我正在使用django-friendship庫。在他們的文檔,他們說:什麼通用視圖應該用於在drf中創建好友請求?

建立友好關係請求:

other_user = User.objects.get(pk=1) 
Friend.objects.add_friend(
    request.user,        # The sender 
    other_user,         # The recipient 
    message='Hi! I would like to add you')  # This message is optional 

我的問題是應該在哪裏這個代碼編寫。我知道它屬於一種觀點,但是什麼樣的觀點?有人能給我一個例子嗎?

回答

1

我可能會將它添加到處理用戶友誼的任何更新的視圖。例如,如果您有處理通過某個端點提交好友請求的視圖,它可能如下所示:

class CreateFriendRequestView(APIView): 
    def post(self, request, *args, **kwargs): 
     other_user = User.objects.get(pk=request.data['other_user']) 
     Friend.objects.add_friend(
      request.user,        
      other_user,         
     message='Hi! I would like to add you') 
     return Response({'status': 'Request sent'}, status=201) 
+0

我是否必須返回響應? –

+0

@TomFinet這取決於你,我只是這麼做的,因爲REST api通常會承認請求已被正確處理。 – mattjegan

+0

這是最佳做法嗎? –