【问题标题】:Index Error: list index out of range in Django索引错误:Django 中的列表索引超出范围
【发布时间】:2015-05-04 11:29:39
【问题描述】:

我正在使用 Django 1.7 和 Django Rest Framework。我编写了一个检测用户登录的 API,如下所示:

def login_check(request):
    user = request.user
    if user.is_anonymous():
        return HttpResponse(json.dumps({
            'success': False
        }))
    else:
        try:
            user_obj = UserProfile.objects.get(user__pk=user.id)
        except UserProfile.DoesNotExist:
            main_obj = User.objects.get(pk=user.id)
            user_obj = UserProfile(user=main_obj)
            user_obj.save()
        fb_uid = SocialAccount.objects.filter(user_id=user.id, provider='facebook')
        print fb_uid[0].uid
        user_obj.profile_photo_url = "http://graph.facebook.com/{}/picture?width=300&height=300".format(fb_uid[0].uid)
        user_obj.save()
        serialized = UserProfileSerializer(user_obj)
        return Response(serialized.data, status=status.HTTP_200_OK)

我在这个视图中遇到了一个错误,它显示了以下回溯

IndexError at /loginCheck/
list index out of range
Request Method: GET
Request URL:    http://localhost:8000/loginCheck/
Django Version: 1.7.4
Exception Type: IndexError
Exception Value:    
list index out of range
Exception Location: f:\App\venv\lib\site-packages\django\db\models\query.py in __getitem__, line 178
Python Executable:  f:\App\venv\Scripts\python.exe
Python Version: 2.7.6
Python Path:    
['f:\\App',
 'f:\\App\\venv\\lib\\site-packages\\psycopg2-2.6-py2.7-win32.egg',
 'C:\\WINDOWS\\SYSTEM32\\python27.zip',
 'f:\\App\\venv\\DLLs',
 'f:\\App\\venv\\lib',
 'f:\\App\\venv\\lib\\plat-win',
 'f:\\App\\venv\\lib\\lib-tk',
 'f:\\App\\venv\\Scripts',
 'c:\\Python27\\Lib',
 'c:\\Python27\\DLLs',
 'c:\\Python27\\Lib\\lib-tk',
 'f:\\App\\venv',
 'f:\\App\\venv\\lib\\site-packages']

我不完全确定这是我的代码或 Django 的 query.py 中的错误。我会很感激帮助解决这里的问题

【问题讨论】:

  • 当搜索返回空结果时,print fb_uid[0].uid 行可能有问题。
  • 你检查过SocialAccount.objects.filter实际上返回了一个不为空的列表吗?您可以在通话后立即尝试print len(fb_uid)。当没有结果时,您可能需要处理更多的防御性代码。

标签: python django


【解决方案1】:

尝试使用first()方法代替[0]查询集的索引:

so_account = SocialAccount.objects.filter(user_id=user.id,
                                          provider='facebook').first()
if so_account:
    fb_uid = so_account.uid
    ...

【讨论】:

  • 过滤函数的返回类型总是django.db.models.query.QuerySet。如果查询集中有 2 条以上的记录,是否无法获得像 so_account[2] 这样的记录之一?那为什么记录数是1就不能用so_account[0]
  • 如果记录数为1(或更多),则可以使用so_account[0]。但是如果记录数为零,那么IndexError就会被抛出。
【解决方案2】:

在 django 中documentation

说:

Entry.objects.order_by('headline')[0]
Entry.objects.order_by('headline')[0:1].get()

但是请注意,如果没有对象符合给定条件,第一个将引发 IndexError,而第二个将引发 DoesNotExist。有关详细信息,请参阅 get()。

因此,如果有可能,您的查询将根本不返回任何数据。您可能想使用Entry.objects.order_by('headline')[0:1].get() 而不是它的快捷方式[0]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-18
    • 2017-10-30
    • 1970-01-01
    相关资源
    最近更新 更多