import itertools


def object_to_dict(instance):
    """
    Similar to django.forms.models.model_to_dict() but more comprehensive.

    Taken from https://stackoverflow.com/questions/21925671/#answer-29088221
    with a minor tweak: .id --> .pk
    """
    opts = instance._meta
    data = {}
    for f in itertools.chain(opts.concrete_fields, opts.private_fields):
        data[f.name] = f.value_from_object(instance)
    for f in opts.many_to_many:
        data[f.name] = [i.pk for i in f.value_from_object(instance)]
    return data