Django GET请求下在Serializer方法字段中获取当前用户对象时出现KeyError: 'request'的解决求助
Hey there, let's break down why you're hitting this KeyError: 'request' and fix it right away.
问题根源
The error pops up in your get_can_vote method, but the real issue lies in the get_replys method of your StockUserCommentsOutputSerializer1 serializer.
When you initialize the main serializer in your view, you correctly pass context={'request':request}. However, when you recursively create a serializer for the reply comments, you don't pass along this context. The child serializer for replies ends up with an empty context dictionary, so when it tries to access self.context['request'] in get_can_vote, it throws the KeyError.
解决方案
1. 修复递归序列化器调用
Update your get_replys method to pass the current serializer's context to the child serializer:
def get_replys(self, obj): queryset = StockUserComments.objects.filter(parent_id=obj.id).order_by('date') # 传递当前上下文给子序列化器 serializer = StockUserCommentsOutputSerializer1(queryset, many=True, context=self.context) return serializer.data
2. 可选:增加安全回退机制
To make your code more robust (in case the context ever lacks the request object), modify get_can_vote to use .get() instead of direct key access. This prevents unexpected KeyErrors and handles unauthenticated users gracefully:
def get_can_vote(self, obj): # 使用get()避免context中没有request时抛出KeyError request = self.context.get('request') if not request or not request.user.is_authenticated: return False # 根据业务需求处理未认证用户的情况 user = request.user if obj.id: # 简化判断逻辑:如果存在投票记录则返回False,否则返回True return not CommentVotes.objects.filter(voter=user, comment=obj.id).exists() return False
为什么这样有效
When you pass context=self.context to the child serializer, it inherits the request object from the parent serializer's context. This ensures that every instance of StockUserCommentsOutputSerializer1 (whether parent or reply) has access to the request, so get_can_vote can retrieve the current user without errors.
内容的提问来源于stack exchange,提问作者sivaperumal10000

