In Django shortcuts there is a function get_object_or_404 , but there is no function get_object_or_none , which can be useful in the case when we do not want to cause error 404 immediately, but we need to perform some actions in case the object does not exist in the database data.
It was possible to find a discussion on the Internet, where developers wrote that such a functional can be easily implemented as a function until a function within the project of the developer and it is not required to introduce it into the main code.
I needed this functionality to search for tags on the site.
So I added it to the core of the site as a shortcut.
# -*- coding: utf-8 -*- def get_object_or_none(klass, *args, **kwargs): try: return klass._default_manager.get(*args, **kwargs) except klass.DoesNotExist: return None
def get_queryset(self, **kwargs): q = self.request.GET.get('q') tag = get_object_or_none(Tag, name=q) if tag: return TaggedItem.objects.all().filter(tag=tag) return