views:

26

answers:

1

I want to retrieve the most recently added element and if there is none at all, assign some default values such as:

query = X.objects.filter(name="aa",type="b")[0]
if query:
    resultname =query.name
    resulttype = query.type
else:
    resultname = "a default name"
    resulttype = "a default type"

This is not working as it will raise an exception when the first line, query = X.objects.filter(name="aa",type="b")[0], executes and the filtered query list is empty.

A: 

Indexing a QuerySet results in a single model, if any exist. Either catch the exception if none exist, or use len() beforehand on the QuerySet to see if any records were found.

Ignacio Vazquez-Abrams
what would be the related exception if none exists? Thanks
Hellnar
Dunno. Try it and check the logs.
Ignacio Vazquez-Abrams
except IndexError: seems to fix it, ty
Hellnar