About Silent Database Record Retrieval
Usually, you get a single object from a model using manager's get()
method, like this:
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:
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
Also by me
Django Paddle Subscriptions app
For Django-based SaaS projects.
Django GDPR Cookie Consent app
For Django websites that use cookies.