Django TypeError:键必须是str、int、float、bool或None,而不是News Chann

2024-06-16 09:37:17 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的登录视图。在

def login(request):
    username = request.data.get("username")
    password = request.data.get("password")
    if username is None or password is None:
        return Response({'error': 'Please provide both username and password'},
                        status=HTTP_400_BAD_REQUEST)
    user = authenticate(username=username, password=password)
    if not user:
        return Response({'error': 'Invalid Credentials'},
                        status=HTTP_404_NOT_FOUND)
    token, _ = Token.objects.get_or_create(user=user)
    voting_result = Count.objects.filter(userId=user.id)
    print(voting_result)
    channel = {}

    for e in voting_result:
        channel[e.channelId] = e.rate
    return Response({'token': token.key, 'user': user.username, 'email': user.email, 'id': user.id, 'stats': channel},
                    status=HTTP_200_OK)

我想在我的回复中添加一个dictionary频道。但是我得到了这个错误。在

^{pr2}$

我该怎么做才能让频道词典也出现在我的回答中?我将在我的react应用程序中使用它。在


Tags: tokenidhttpdatagetreturnresponserequest
2条回答

看起来您需要channelIdid作为密钥

尝试:

for e in voting_result:
    channel[e.channelId.id] = e.rate

Python dicts只能处理不可变的散列键,如str、int、float、bool、tuple、frozenset等。如果一个实体不可哈希或可变,它就不能是字典键。如果要使用e.channelId作为键,则应将其转换为字符串,例如:

channel[str(e.channelId)] = e.rate

相关问题 更多 >