[Django]-Django DoesNotExist Best Practices

6👍

First, accessing the first item in the QuerySet via index:

Users.objects.filter()[0]

would throw an IndexError if there is no object at position 0, not a DoesNotExist exception.

When checking for a non-existent object, I opt for:

try:
    User.objects.get(pk=1)
except User.DoesNotExist:
    # do something else

try:
    Post.objects.get(pk=1)
except Post.DoesNotExist:
    # do something else

However, you could do:

user = User.objects.filter(pk=1).first()
post = Post.objects.filter(pk=1).first()

if not all([user, post]):
    # do something else

.first() returns None if no object is found. Reference: https://docs.djangoproject.com/en/1.9/ref/models/querysets/#first

or also:

user = get_object_or_404(User, pk=1)

Reference: https://docs.djangoproject.com/en/1.9/topics/http/shortcuts/#get-object-or-404

Which methodology you choose largely depends on your specific use case.

Leave a comment