sierra101
sierra101

Reputation: 13

Django : IndexError: list index out of range

Getting exception :

IndexError django.db.models.sql.compiler in apply_converters

IndexError: list index out of range in djagno queryset

I am doing this

object =Info.objects.get(is_active=False,device_id=device_id)

here device_id is long text type in database schema and it is indexed

object =Info.objects.get(is_active=False,device_id=device_id)

Upvotes: 0

Views: 1256

Answers (2)

Abin Abraham
Abin Abraham

Reputation: 517

You are using get method to fetch object.

Given query

object =Info.objects.get(is_active=False,device_id=device_id)

In this, device_id or is_active matching query might not be exist.

either you can use try, except method in get.

try:
    object =Info.objects.get(is_active=False,device_id=device_id)
except:
    object = None

or You have to use filter method

object =Info.objects.filter(is_active=False,device_id=device_id)[0]

OR

object =Info.objects.filter(is_active=False,device_id=device_id).first()

filter query will result None if query is not fetching data. Will not throw error for conditions not matching case.

Upvotes: 1

slqq
slqq

Reputation: 265

You could try with .first() and it would be like:

object = Info.objects.filter(is_active=False, device_id=device_id).first()

Upvotes: 1

Related Questions