Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access the related ForeignKey object from a object in SQLAlchemy?

For example,

I have an object mapped to a table. IE:

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

When I do object.location, I get the actual foreignkey value. But I don't want that, how can I get the object instead (like in Django ORM). Thanks!

like image 499
nubela Avatar asked Sep 14 '11 17:09

nubela


1 Answers

If you're using declarative base objects (which is recommended if you want it more like Django) then:

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")

See the relationship docs

like image 107
six8 Avatar answered Sep 19 '22 10:09

six8