[Python] How to set up one-to-many relationship in SQLAlchemy?

Discussão em 'Python' iniciado por Stack, Janeiro 30, 2025.

  1. Stack

    Stack Membro Participativo

    I want to ask for help with SQLAlchemy in Python. I want to set up one-to-many relationship with tasks and users. The task can have only one solver, but the user could solve many tasks. Making it via ForeignKey makes no sense for me, because I want to be able to access all tasks solved by user without doing iteration over all tasks in order to find ones that is solved by that user, also I want to be able to access the solver from the task. I have read the docs about relationship() in SQLAlchemy, but it seems like I am in the fog. Can you help me with setting this up?

    class User(Base):
    __tablename__ = 'users'

    id: Mapped[int] = mapped_column(primary_key=True)
    # Here should go the relationship to all solved tasks


    class Task(Base):
    __tablename__ = 'tasks'

    id: Mapped[int] = mapped_column(primary_key=True)
    text: Mapped[str] = mapped_column(String(4096))
    # This should be replaced with relationship to user
    solver: Mapped[int] = mapped_column(ForeignKey('users.id'))

    Continue reading...

Compartilhe esta Página