I was facing with the same problem too. It's hard to write and read try-except
for each time when you want to get an element from your model as in @Arthur Debert's answer. So, my solution is to create an Getter
class which is inherited by the models:
class Getter:
@classmethod
def try_to_get(cls, *args, **kwargs):
try:
return cls.objects.get(**kwargs)
except Exception as e:
return None
class MyActualModel(models.Model, Getter):
pk_id = models.AutoField(primary_key=True)
...
In this way, I can get the actual element of MyActualModel
or None
:
MyActualModel.try_to_get(pk_id=1)