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

后端 未结 19 1517
清酒与你
清酒与你 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:54

    To make things easier, here is a snippet of the code I wrote, based on inputs from the wonderful replies here:

    class MyManager(models.Manager):
    
        def get_or_none(self, **kwargs):
            try:
                return self.get(**kwargs)
            except ObjectDoesNotExist:
                return None
    

    And then in your model:

    class MyModel(models.Model):
        objects = MyManager()
    

    That's it. Now you have MyModel.objects.get() as well as MyModel.objetcs.get_or_none()

提交回复
热议问题