<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def expand(obj, relation, seen):
 """ Return the to_json or id of a sqlalchemy relationship. """


    if hasattr(relation, 'all'):
        relation = relation.all()

    if hasattr(relation, '__iter__'):
        return [expand(obj, item, seen) for item in relation]

    if type(relation) not in seen:
        return to_json(relation, seen + [type(obj)])
    else:
        return relation.id