当我尝试运行此命令时,我正在使用登录api
user_profile = UserProfile.objects.filter(user_id=user.id).values('usertype')
它给了我这个错误:AttributeError: 'QuerySet' object has no attribute 'usertype'
,但是在控制台中,我检查了我是否获得了它的查询集<QuerySet [{'usertype': 2}]>
,但无法从中获取值,有人可以帮助我如何解决此问题?这是我的登录功能
class Login(APIView):
permission_classes = (AllowAny,)
def post(self, request):
username = request.data.get("username")
password = request.data.get("password")
if username is None or password is None:
return Response({'success': False, 'error': 'Please provide both username and password'},
status=HTTP_400_BAD_REQUEST)
user = authenticate(username=username, password=password)
# return Response({'success': True, 'user': user},status=HTTP_200_OK)
if not user:
return Response({'success': False, 'error': 'Invalid Credentials'},
status=HTTP_400_BAD_REQUEST)
access_token, refresh_token = utils.generate_tokens(user)
user_profile = UserProfile.objects.filter(user_id=user.id).values('usertype')
print(user_profile.usertype)
答案 0 :(得分:1)
user_profile
是一个QuerySet
对象,就像一个可迭代的 list
。如果要访问 usertype
,则应使用数组索引或循环
print(user_profile[0]['usertype']) # this will print data from the first item
for item in user_profile:
print(item['usertype'])