How do I get the object if it exists, or None if it does not exist?

后端 未结 19 1502
清酒与你
清酒与你 2020-11-28 01:14

When I ask the model manager to get an object, it raises DoesNotExist when there is no matching object.

go = Content.objects.get(name=\"baby\")
         


        
19条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-28 01:50

    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)
    

提交回复
热议问题