samedi 25 juin 2016

Migrating from SQLAlchemy core to ORM

Currently we only use SQLAlchemy core, so all the tables are defined using Table. Now, we would like to incrementally port the existing Tables to ORM and have new Tables use ORM from scratch.

As an example, say we currently have

Users = Table(
    'users', # Table name
    metadata,
    Column('id', String, primary_key=True),
    Column('name', String),
    Column('email_address', String),
)

and we'd like to add a Posts table using the ORM, something like

class Posts(Base):
    __tablename__ = 'posts'
    id = Column(Integer, primary_key=True)
    contents = Column(String(300))

How do I update the Users table to reflect the fact that a user can have multiple Posts ? The intended end goal is to have something like

Users = Table(
    'users', # Table name
    metadata,
    Column('id', String, primary_key=True),
    Column('name', String),
    Column('email_address', String),

    # How to express the equivalent of this ?
    posts = relationship("Posts", back_populates="submitter")
)

class Posts(Base):
    __tablename__ = 'posts'
    id = Column(Integer, primary_key=True)
    contents = Column(String)
    submitter = relationship("Users", back_populates="posts")

Is it possible to do this ? Or will I have to convert the Users table to ORM before doing something like this ?

Aucun commentaire:

Enregistrer un commentaire