Django 'dict' object has no attribute 'user_id'

五迷三道 提交于 2020-07-08 04:57:10

问题


I get the following error 'dict' object has no attribute 'user_id' but not sure I understand the error. Since user_id is available from the queryset.

Error happens at the last line of code

users_who_played = UserEvent.objects\
            .values('user_id')\
            .annotate(total_season_points=Sum('points'))\
            .filter(event__season_id=season.id)\
            .order_by('-total_season_points')\

    for i, user_who_played in enumerate(users_who_played):

        try:
            user = UserSeason.objects.
                   get(user=user_who_played.user_id, season=season.id)

回答1:


The .values() method on querysets returns a queryset that returns dictionaries instead of model objects when you iterate over it -- so user_who_played is a dict, which means you should access the user id by writing user_who_played['user_id'] instead of using dot attribute syntax.

If you want to retrieve only certain fields from the database but still want to deal with model objects, an alternative is to use the .only() method instead of .values().



来源:https://stackoverflow.com/questions/25632197/django-dict-object-has-no-attribute-user-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!