3/21/2017 - 2:47 AM

django model utils

django model utils

from django.db import models

def get_object_or_none(klass, *args, **kwargs):
    Uses get() to return an object or None if the 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.

    See also: https://gist.github.com/maxp/213294
    if isinstance(klass, type) and issubclass(klass, models.Model):
        queryset = klass.objects.get_queryset()
    elif isinstance(klass, models.Manager):
        queryset = klass.get_queryset()
        queryset = klass

        return queryset.get(*args, **kwargs)
    except queryset.model.DoesNotExist:
        return None