Skip to content

usecase: how to get the object history data to track obj change in event? #49

@wangxin688

Description

@wangxin688

I try to get object change using following code, but MutableJSON has no history getted

def get_object_changes(obj):
    """Given a model instance, returns dict of pending
    changes waiting for database flush/commit.

    e.g. {
        "pre_change": {},
        "post_change": {},
        "diff": {}
    }
    """
    inspection = inspect(obj)
    changes = {
        "pre_change": {},
        "post_change": {},
        "diff": {},
    }
    for attr in class_mapper(obj.__class__).column_attrs:
        if getattr(inspection.attrs, attr.key).history.has_changes():
            if get_history(obj, attr.key)[2]:
                before = get_history(obj, attr.key)[2].pop()
                after = getattr(obj, attr.key)
                changes["pre_change"][attr.key] = before
                changes["post_change"][attr.key] = after
                if before != after:
                    if before or after:
                        changes["diff"][attr.key] = {"before": before, "after": after}
    return jsonable_encoder(changes)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions