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

后端 未结 19 1539
清酒与你
清酒与你 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条回答
  •  萌比男神i
    2020-11-28 01:55

    This is a copycat from Django's get_object_or_404 except that the method returns None. This is extremely useful when we have to use only() query to retreive certain fields only. This method can accept a model or a queryset.

    from django.shortcuts import _get_queryset
    
    
    def get_object_or_none(klass, *args, **kwargs):
        """
        Use get() to return an object, or return None if object
        does not exist.
        klass may be a Model, Manager, or QuerySet object. All other passed
        arguments and keyword arguments are used in the get() query.
        Like with QuerySet.get(), MultipleObjectsReturned is raised if more than
        one object is found.
        """
        queryset = _get_queryset(klass)
        if not hasattr(queryset, 'get'):
            klass__name = klass.__name__ if isinstance(klass, type) else klass.__class__.__name__
            raise ValueError(
                "First argument to get_object_or_none() must be a Model, Manager, "
                "or QuerySet, not '%s'." % klass__name
            )
        try:
            return queryset.get(*args, **kwargs)
        except queryset.model.DoesNotExist:
            return None
    

提交回复
热议问题