这是我的登录视图。
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)
我想在回复中添加词典频道。但是我遇到了这个错误。
keys must be str, int, float, bool or None, not News_Channel
我应该怎么做才能使我的回复中也有 channel 词典?我将在我的应用程序中使用它。
答案 0 :(得分:1)
Python字典只能处理不可变的可哈希键,例如str,int,float,bool,tuple,frozenset等。如果实体不可哈希或可变,则它不能作为字典键。如果要使用e.channelId
作为键,则应将其转换为字符串,例如:
channel[str(e.channelId)] = e.rate
答案 1 :(得分:1)
好像您需要channelId
id作为密钥
尝试:
for e in voting_result:
channel[e.channelId.id] = e.rate