我想获得当前用户ID传递
class document_typeViewSet(viewsets.ModelViewSet):
user = User.objects.get(id=request.user.id)
group = user.group.get()
queryset = document_type.objects.filter(role_id=group)
serializer_class = document_typeSerializer
我收到错误AttributeError: module 'request' has no attribute 'user'
"
答案 0 :(得分:1)
更新您的代码:
class document_typeViewSet(viewsets.ModelViewSet):
def function_name(self, request):
user = User.objects.get(id=request.user.id)
group = user.group.get()
queryset = document_type.objects.filter(role_id=group)
serializer_class = document_typeSerializer
然后你会得到request.user.id
。
答案 1 :(得分:1)
假设您在USER
(新实例创建)时需要creation
个实例,那么您必须覆盖create()
,如下所示,
class document_typeViewSet(viewsets.ModelViewSet):
queryset = document_type.objects.filter(role_id=group)
serializer_class = document_typeSerializer
def get_user(self, request):
return request.user
def create(self, request, *args, **kwargs):
# create new "document_type" instance
current_user = request.user
# do something with "current_user"
return super().create(request, *args, **kwargs)
同样,如果您有有效logged-in
对象
request
用户