[Fixed]-Index Error: list index out of range in Django

24👍

Try to use the first() method instead of [0] indexing of queryset:

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

-1👍

In the django documentation

Says that:

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

Note, however, that the first of these will raise IndexError while the second will raise DoesNotExist if no objects match the given criteria. See get() for more details.

So if that is possible that your query will return no data at all. You might want to use Entry.objects.order_by('headline')[0:1].get() instead of its shortcut [0]

Leave a comment