Python / DRF - 尝试序列化字典时出错

Python / DRF - error when trying to serialize a dictionary

我有以下词典:

<type 'dict'>: {u'user2': {'username': u'user2', 'problems_attempts_last_week': None, 'videos_last_week': None, 'correct_problems_last_week': None, 'videos_overall': None, 'problems_overall': None, 'problems_attempts_overall': None, 'correct_problems_overall': None, 'forum_posts_last_week': 2, 'forum_posts_overall': 13, 'date_last_active': datetime.datetime(2019, 8, 23, 0, 0, tzinfo=<UTC>), 'problems_last_week': None}, 
u'user3': {'username': u'user3', 'problems_attempts_last_week': None, 'videos_last_week': None, 'correct_problems_last_week': 6, 'videos_overall': None, 'problems_overall': 18, 'problems_attempts_overall': 3, 'correct_problems_overall': 15, 'forum_posts_last_week': None, 'forum_posts_overall': None, 'date_last_active': datetime.datetime(2019, 8, 23, 0, 0, tzinfo=<UTC>), 'problems_last_week': 6}, 
u'user1': {'username': u'user1', 'problems_attempts_last_week': 4, 'videos_last_week': 1, 'correct_problems_last_week': None, 'videos_overall': 3, 'problems_overall': 8, 'problems_attempts_overall': 4, 'correct_problems_overall': 4, 'forum_posts_last_week': 2, 'forum_posts_overall': 2, 'date_last_active': datetime.datetime(2019, 8, 23, 0, 0, tzinfo=<UTC>), 'problems_last_week': 4}}

以及它的以下序列化程序:

class UserEngagementSerializer(serializers.Serializer):
    """
    Serializes row data
    """
    username = serializers.CharField()
    videos_overall = serializers.IntegerField()
    videos_last_week = serializers.IntegerField()
    problems_overall = serializers.IntegerField()
    problems_last_week = serializers.IntegerField()
    correct_problems_overall = serializers.IntegerField()
    correct_problems_last_week = serializers.IntegerField()
    problems_attempts_overall = serializers.IntegerField()
    problems_attempts_last_week = serializers.IntegerField()
    forum_posts_overall = serializers.IntegerField()
    forum_posts_last_week = serializers.IntegerField()
    date_last_active = serializers.DateTimeField(format=settings.DATE_FORMAT)

当我尝试 return 我的 REST 服务的结果时,显示以下错误:

AttributeError: Got AttributeError when attempting to get a value for field username on serializer UserEngagementSerializer. The serializer field might be named incorrectly and not match any attribute or key on the unicode instance. Original exception text was: 'unicode' object has no attribute 'username'.

这个序列化程序在我 return 直接 Django 查询集时工作。我如何让它与字典一起使用?

发生这种情况是因为 Python 将 'username' 值视为 unicode。这可能是由您从中检索数据的来源引起的。在将字典传递给序列化程序之前,您需要确保将键 'username' 的值编码为 UTF-8 或 ASCII:

dict["username"].encode("utf-8")

我强烈建议您升级到 python3

serializer = UserEngagementSerializer(u['user2'])
print(serializer.data)