SQLAlchemy: get relationships from a db.Model

前端 未结 3 1439
星月不相逢
星月不相逢 2020-12-15 20:32

I need to get a list of a model\'s properties which are actually relationships (that is, they were created by relationship()).

Say I have a model

相关标签:
3条回答
  • 2020-12-15 20:51

    There is indeed - take a look at sqlalchemy.inspection.inspect. Calling inspect on a mapped class (for example, your Thing class) will return a Mapper, which has a relationships attribute that is dict like:

    from sqlalchemy.inspection import inspect
    
    thing_relations = inspect(Thing).relationships.items()
    
    0 讨论(0)
  • 2020-12-15 21:03

    Instead of using inspect you can also use

    model.__mapper__.relationships

    0 讨论(0)
  • 2020-12-15 21:06

    You just need to use the inspect module from sqlalchemy

    from sqlalchemy import inspect
    
    i = inspect(model)
    i.relationships
    

    If you need the class of each referred model you can do:

    referred_classes = [r.mapper.class_ for r in i.relationships]
    
    0 讨论(0)
提交回复
热议问题