可以在SQLAlchemy中设置类似rails的关联吗?

tri*_*nth 2 python orm sqlalchemy ruby-on-rails associations

在Rails中,您可以设置关联,这样如果您有文章和类别模型,并且"类别"是"文章"列,您可以执行以下操作:

article.category --> returns the category Object
Run Code Online (Sandbox Code Playgroud)

但是在SQLAlchemy中,我只能这样做:

article.category --> only returns the category's id
Run Code Online (Sandbox Code Playgroud)

有没有办法使用SQLAlchemy获取Category对象?我目前正在使用声明式定义模型.

Nil*_*esh 6

你可以创建像这样的关系

category_id = Column(Integer, ForeignKey('category.id'))
category = relationship('Category')
Run Code Online (Sandbox Code Playgroud)

这样,您将在访问类别时获取对象.

  • 我感谢您发布答案,而不是仅仅通过文档惩罚提问者. (3认同)