Django: Get an object form the DB, or 'None' if nothing matches

后端 未结 8 1474
粉色の甜心
粉色の甜心 2020-11-30 02:45

Is there any Django function which will let me get an object form the database, or None if nothing matches?

Right now I\'m using something like:

foo          


        
8条回答
  •  一生所求
    2020-11-30 03:09

    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, *args, **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(*args, **kwargs)
        except model.DoesNotExist:
            return None
    

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

    1. obj = get_unique_or_none(Model, *args, **kwargs) as previosuly discussed
    2. obj = get_unique_or_none(Model, parent.children, *args, **kwargs)

提交回复
热议问题