Skip to main content
 首页 » 编程设计

python之在 drf 中应该使用什么通用 View 来创建好友请求

2025年02月15日898°冷暖

我正在为我的 Android 应用构建一个 drf 后端 API。我需要 API 才能从用户向相关用户发送好友请求。为此,我使用了 django-friendship图书馆。他们在文档中说:

Create a friendship request:

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 

我的问题是这段代码应该写在哪里。我知道它属于一个 View ,但是什么样的 View 呢?有人可以给我举个例子吗?

请您参考如下方法:

我可能会将其添加到处理用户友谊更新的 View 中。例如,如果您有一个 View 通过某个端点处理好友请求的提交,它可能如下所示:

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)