如何在 SQLalchemy 中查询多个表的关系?

How can I query multiple tables relationship in SQLalchemy?

我有这个 table 与多个 table 关系


class _FoodsInStock(Base):
    __tablename__ = 'FoodsInStock'

    date = Column(String, primary_key=True)

    breakfasts = relationship('_BreakfastsInStock')
    lunch = relationship('_LunchInStock')
    snacks = relationship('_SnacksInStock')
    cereals = relationship('_CerealsInStock')
    fruits = relationship('_FruitsInStock')
    cookies = relationship('_CookiesInStock')
    chocolates = relationship('_ChocolatesInStock')
    others = relationship('_OtherFoodsInStock')


我正在尝试获取与 _FoodsInStock table

相关的特定 table

我知道我可以做这么简单的事情:


table = _FoodInStock.query.get(id).breakfasts

效果很好,但我需要根据某些输入获得 table 相关信息,这样做需要我每行写一行

有什么方法可以根据输入使 table 相关联吗? 像字典里的东西:


tables = ['breakfasts', 'lunch', 'snacks', 'cereals', 'fruits', 'cookies', 'chocolates', 'others']

for table in tables:

    q = _FoodInStock.query.get(id)[table]

谢谢!

由于这些是属性,您应该可以通过 getattr:

实现
tables = ['breakfasts', 'lunch', 'snacks', 'cereals', 'fruits', 'cookies', 'chocolates', 'others']

for table in tables:
    q = getattr(_FoodInStock.query.get(id), table)