About Silent Database Record Retrieval

Usually, you get a single object from a model using manager's get() method, like this:

1
category = Category.objects.get(slug="default")

But this method raises exceptions when the query returns empty result or when there are duplicates with the same search conditions.

To be more flexible, you can combine filter() and first() instead:

1
2
if category := Category.objects.filter(slug="default").first():
    # do something with the category

It returns None in case if the record doesn't exist, or the first record with the given lookup.

Tips and Tricks Programming Django 5.x Django 4.2 Django 3.2