如何从SQLAlchemy中的对象访问相关的ForeignKey对象?

例如,

我有一个映射到表的对象. IE:

location = db.Column(db.Integer, db.ForeignKey('location.id'))

当我做object.location时,我得到实际的foreignkey值.但我不想那样,我怎样才能得到对象(比如在Django ORM中).谢谢!

最佳答案 如果您正在使用声明性基础对象(如果您希望它更像Django,建议使用它),那么:

class Child(Base):
    __tablename__ = 'child'
    id = Column(Integer, primary_key=True)

class Parent(Base):
    __tablename__ = 'parent'
    id = Column(Integer, primary_key=True)
    child_id = Column(Integer, ForeignKey('child.id'))
    child = relationship("Child", backref="parents")

relationship docs

点赞