def _unique_todict(session, cls, queryfunc, arg, kw):
    '''
    Checks if ORM entity exists according to criteria,
    if yes, returns it, if no, returns dict representation
    (required for further DB replication and syncing)
    '''
    q = session.query(cls)
    q = queryfunc(q, *arg, **kw)
    obj = q.first()
    if not obj:
        obj = kw
        obj['__cls__'] = cls.__mapper__.class_.__name__
    return obj