尝试序列化词典时出现Python/DRF错误

2024-04-20 07:30:31 发布

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

我有以下词典:

<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)

当我尝试从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'.

当我直接返回Django查询集时,这个序列化程序就工作了。我怎样才能用这本词典?你知道吗


Tags: nonedatetimedateusernameforumvideoslastposts
2条回答

我强烈建议您升级到python3

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

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

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

相关问题 更多 >