employee = Employee.objects.filter('age' = 99)
We assume this queryset is empty.
If I use employee[0], that will return index out of range error, so is it possible to have a None as default value here?
`employee[0] or None`? # This won't work, but this is what I mean.
If you just want to get a single instance, use
get, notfilter:If that doesn’t exist, you’ll get a
Employee.DoesNotExistexception, which you’ll need to catch. If there’s more than one 99 year-old employee, you’ll get a Employee.MultipleObjectsReturned exception, which you may want to catch.There’s always django-annoying‘s
get_object_or_Noneif you’re feeling lazy!If you don’t want to use all of django-annoying, you can always add
get_object_or_Nonesomewhere, it just looks like this: