Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django 'dict' object has no attribute 'user_id'

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)
like image 252
Yannick Avatar asked Sep 02 '14 20:09

Yannick


1 Answers

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

like image 150
Ismail Badawi Avatar answered Sep 30 '22 09:09

Ismail Badawi