def patched_model():
    """Context Manager that safely patches django.db.Model.__reduce__()."""

    patched = ('__reduce__', '__getstate__', '__setstate__')
    originals = {}
    for patch in patched:
        try:
            originals[patch] = getattr(models.Model, patch)
        except:
            pass

    try:
        # Patch various parts of the model
        models.Model.__reduce__ = _reduce
        try:
            del models.Model.__getstate__
        except:
            pass
        try:
            del models.Model.__setstate__
        except:  # pragma: no cover
            pass

        yield

    finally:
        # Restore the model
        for patch in patched:
            try:
                setattr(models.Model, patch, originals[patch])
            except KeyError:
                try:
                    delattr(models.Model, patch)
                except AttributeError:
                    pass