'Looks up an object with the given kwargs, creating one if necessary.
Returns a tuple of (object, created), where created is a boolean
specifying whether an object was created.'

def get_or_create(self, **kwargs):

    assert kwargs, 'get_or_create()    must    be    passed    at    least    one    keyword    argument'
    defaults = kwargs.pop('defaults', {})
    lookup = kwargs.copy()
    for f in self.model._meta.fields:
        if (f.attname in lookup):
            lookup[f.name] = lookup.pop(f.attname)
    try:
        self._for_write = True
        return (self.get(**lookup), False)
    except self.model.DoesNotExist:
        try:
            params = dict([(k, v) for (k, v) in kwargs.items() if ('__' not in k)])
            params.update(defaults)
            obj = self.model(**params)
            sid = transaction.savepoint(using=self.db)
            obj.save(force_insert=True, using=self.db)
            transaction.savepoint_commit(sid, using=self.db)
            return (obj, True)
        except IntegrityError as e:
            transaction.savepoint_rollback(sid, using=self.db)
            try:
                return (self.get(**lookup), False)
            except self.model.DoesNotExist:
                raise e
