def extract_object(model_cls, object_or_id, allow_none=False, queryset=None):
    """
    Returns a model instance given the instance itself or its ID.

    If ``queryset`` is provided, it is used to retrieve the object.

    :raise ObjectDoesNotExist: if ID is given but doesn't exist.
    """
    if object_or_id is None and allow_none:
        return None
    elif isinstance(object_or_id, model_cls):
        return object_or_id

    try:
        oid = int(object_or_id)
    except (TypeError, ValueError):
        assert False, '{} is not a numeric ID or {} instance'.format(
            object_or_id, model_cls.__class__.__name__)

    if queryset is not None:
        return queryset.get(pk=oid)
    else:
        return model_cls.objects.get(pk=oid)