'How to gracefully handle DoesNotExist exception when admin user is not found?

I have a created_by field in my model which defaults to the admin user upon object creation. I am fetching the admin user using this piece of code,

admin_user_name = settings.ADMIN_USER_NAME
admin = User.objects.get(username=admin_user_name)

Now if I have to handle the object.DoesNotExist exception like

try:
   admin_user_name = settings.ADMIN_USER_NAME
   admin = User.objects.get(username=admin_user_name)
except User.DoesNotExist:
    # handle the exception gracefully

How do I handle the exception without throwing an error in such a case?

Update: The created_by field is made available by inheriting the following

class AbstractUserBase(models.Model):
    created_by = models.ForeignKey(User,related_name='%(class)s_createdby',on_delete=models.CASCADE)

    class Meta:
        abstract = True


Solution 1:[1]

don't use get. Use ….objects.filter() and count() the result.

An other way would be using ….objects.exists(XYZ) before getting it with get.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1