Concepts 🚀 Project 🧮 Labs
📚 Learn / Databases & SQL / Relationships & joins

Relationships & joins

ForeignKey + relationship() lets you walk from a User to their Models with no SQL.

Code example

class User(Base):
    models = relationship('Model', back_populates='user')

class Model(Base):
    user_id = Column(Integer, ForeignKey('users.id'))
    user = relationship('User', back_populates='models')

user = db.query(User).first()
print(user.models)  # [<Model 1>, <Model 2>, ...]

How it works

Foreign keys declare 'this column points to a row in another table'. relationship() tells SQLAlchemy how to walk the join — user.models runs a lazy SELECT the first time you access it. back_populates keeps both sides in sync: setting model.user = some_user automatically appends model to some_user.models. OpenBenchML uses this for User→Models, Dataset→BenchmarkJobs, Competition→Submissions, Comment→Replies.

🔍 Where this is used in OpenBenchML app/database/models.py — every model has relationships to its parent/child tables.