toolware/utils/query.py
def get_or_create_unique(klass, defaults, unique_fields):
    """
    Returns a tuple of (instance, created), where `instance` is the retrieved
    or created instance of `klass` and `created` is a boolean specifying whether
    a new object was created. The value for the unique fields must be present in
    the defaults dictionary.
    """
    if not unique_fields or not defaults:
        return (None, False)

    uniqueness_query = {k: v for k, v in defaults.items() if k in unique_fields}

    try:
        with transaction.atomic():
            instance, created = klass.objects.get_or_create(defaults=defaults, **uniqueness_query)
    except IntegrityError:
        try:
            instance, created = klass(**defaults).save(), True
        except Exception as err:
            return (None, False)
    except Exception as err:
        return (None, False)

    if instance and not created:
        for attr, value in defaults.items():
            if getattr(instance, attr):
                setattr(instance, attr, value)
        instance.save()

    return (instance, created)
def get_or_create_unique(klass, defaults, unique_fields):
    """
    Returns a tuple of (instance, created), where `instance` is the retrieved
    or created instance of `klass` and `created` is a boolean specifying whether
    a new object was created. The value for the unique fields must be present in
    the defaults dictionary.
    """
    if not unique_fields or not defaults:
        return (None, False)

    uniqueness_query = {k: v for k, v in defaults.items() if k in unique_fields}

    try:
        with transaction.atomic():
            instance, created = klass.objects.get_or_create(defaults=defaults, **uniqueness_query)
    except IntegrityError:
        try:
            instance, created = klass(**defaults).save(), True
        except Exception as err:
            return (None, False)
    except Exception as err:
        return (None, False)

    if instance and not created:
        for attr, value in defaults.items():
            if getattr(instance, attr):
                setattr(instance, attr, value)
        instance.save()

    return (instance, created)
Returns a tuple of (instance, created), where `instance` is the retrieved
    or created instance of `klass` and `created` is a boolean specifying whether
    a new object was created. The value for the unique fields must be present in
    the defaults dictionary.