import six


def get_model_instances(model_class, instances_or_ids, sep=',', ignore_invalid=True, raise_on_error=True):
    """
    Get model instances by ids.
    :param model_class:
    :param instances_or_ids:
    :param sep:
    :param ignore_invalid:
    :param raise_on_error: only effective when ignore_invalid is False. if True, raise error; else add None to results.
    :return:
    """
    results = []
    if isinstance(instances_or_ids, six.string_types):
        instances_or_ids = instances_or_ids.split(sep)

    for item in instances_or_ids:
        if isinstance(item, model_class):
            results.append(item)
        else:
            try:
                results.append(model_class.objects.get(pk=item))
            except Exception as e:
                if not ignore_invalid:
                    if raise_on_error:
                        raise e
                    else:
                        results.append(None)

    return results