1👍
✅
Use filter
instead of get
to test for existence. filter
returns a queryset, which supports the exists
call. get
returns a model instance if one exists, or raises an exception if one does not.
Or just catch the exception, that’s OK too – and is preferable if you’re going to retrieve the object if it exists.
Depending on exactly what you’re trying to do, there may be useful helper/shortcut functions. For instance, get_object_or_404
is useful for the common situation in which you want an object based on a URL parameter and want to return a 404 for parameters that do not match a BD record. get_or_create
is useful when you want to record new information if necessary, and be sure that you have an in-memory object.
Source:stackexchange.com