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

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

    I think it isn't bad idea to use get_object_or_404()

    from django.shortcuts import get_object_or_404
    
    def my_view(request):
        my_object = get_object_or_404(MyModel, pk=1)
    

    This example is equivalent to:

    from django.http import Http404
    
    def my_view(request):
        try:
            my_object = MyModel.objects.get(pk=1)
        except MyModel.DoesNotExist:
            raise Http404("No MyModel matches the given query.")
    

    You can read more about get_object_or_404() in django online documentation.

    0 讨论(0)
  • 2020-11-28 01:40

    Here's a variation on the helper function that allows you to optionally pass in a QuerySet instance, in case you want to get the unique object (if present) from a queryset other than the model's all objects queryset (e.g. from a subset of child items belonging to a parent instance):

    def get_unique_or_none(model, queryset=None, **kwargs):
        """
            Performs the query on the specified `queryset`
            (defaulting to the `all` queryset of the `model`'s default manager)
            and returns the unique object matching the given
            keyword arguments.  Returns `None` if no match is found.
            Throws a `model.MultipleObjectsReturned` exception
            if more than one match is found.
        """
        if queryset is None:
            queryset = model.objects.all()
        try:
            return queryset.get(**kwargs)
        except model.DoesNotExist:
            return None
    

    This can be used in two ways, e.g.:

    1. obj = get_unique_or_none(Model, **kwargs) as previosuly discussed
    2. obj = get_unique_or_none(Model, parent.children, **kwargs)
    0 讨论(0)
  • 2020-11-28 01:41

    You can create a generic function for this.

    def get_or_none(classmodel, **kwargs):
        try:
            return classmodel.objects.get(**kwargs)
        except classmodel.DoesNotExist:
            return None
    

    Use this like below:

    go = get_or_none(Content,name="baby")
    

    go will be None if no entry matches else will return the Content entry.

    Note:It will raises exception MultipleObjectsReturned if more than one entry returned for name="baby".

    You should handle it on the data model to avoid this kind of error but you may prefer to log it at run time like this:

    def get_or_none(classmodel, **kwargs):
        try:
            return classmodel.objects.get(**kwargs)
        except classmodel.MultipleObjectsReturned as e:
            print('ERR====>', e)
    
        except classmodel.DoesNotExist:
            return None
    
    0 讨论(0)
  • 2020-11-28 01:42

    From django docs

    get() raises a DoesNotExist exception if an object is not found for the given parameters. This exception is also an attribute of the model class. The DoesNotExist exception inherits from django.core.exceptions.ObjectDoesNotExist

    You can catch the exception and assign None to go.

    from django.core.exceptions import ObjectDoesNotExist
    try:
        go  = Content.objects.get(name="baby")
    except ObjectDoesNotExist:
        go = None
    
    0 讨论(0)
  • 2020-11-28 01:42

    We can use Django builtin exception which attached to the models named as .DoesNotExist. So, we don't have to import ObjectDoesNotExist exception.

    Instead doing:

    from django.core.exceptions import ObjectDoesNotExist
    
    try:
        content = Content.objects.get(name="baby")
    except ObjectDoesNotExist:
        content = None
    

    We can do this:

    try:
        content = Content.objects.get(name="baby")
    except Content.DoesNotExist:
        content = None
    
    0 讨论(0)
  • 2020-11-28 01:43

    You can do it this way:

    go  = Content.objects.filter(name="baby").first()
    

    Now go variable could be either the object you want or None

    Ref: https://docs.djangoproject.com/en/1.8/ref/models/querysets/#django.db.models.query.QuerySet.first

    0 讨论(0)
提交回复
热议问题