Django'dict'对象没有属性'user_id' [英] Django 'dict' object has no attribute 'user_id'

查看:117
本文介绍了Django'dict'对象没有属性'user_id'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到以下错误 dict对象没有属性 user_id ,但不确定我是否理解该错误。由于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)


推荐答案

.values ()的查询集方法返回一个查询集,当您对其进行迭代时,该查询集将返回字典而不是模型对象 –因此, user_who_played 是一个dict,这意味着您应该通过编写 user_who_played ['user_id'] 来访问用户ID,而不要使用点属性语法。

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.

如果您只想从数据库中检索某些字段,但仍想处理模型对象,则可以选择使用 .only()方法而不是 .values()

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

这篇关于Django'dict'对象没有属性'user_id'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆