alphanumeric
alphanumeric

Reputation: 19379

How to create a single table using SqlAlchemy declarative_base

To create the User table I have to use drop_all and then create_all methods. But these two functions re-initiate an entire database. I wonder if there is a way to create the User table without erasing (or dropping) any existing tables in a database?

import sqlalchemy
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()


class User(Base):
    __tablename__ = 'users'
    id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True)
    name = sqlalchemy.Column(sqlalchemy.String)

    def __init__(self, code=None, *args, **kwargs):
        self.name = name


url = 'postgresql+psycopg2://user:[email protected]/my_db'
engine = sqlalchemy.create_engine(url)
session = sqlalchemy.orm.scoped_session(sqlalchemy.orm.sessionmaker())
session.configure(bind=engine, autoflush=False, expire_on_commit=False)

Base.metadata.drop_all(engine)
Base.metadata.create_all(engine)

Upvotes: 26

Views: 26720

Answers (2)

Arnab De
Arnab De

Reputation: 462

Another way to accomplish the task:

Base.metadata.tables['users'].create(engine)
Base.metadata.tables['users'].drop(engine)

Upvotes: 3

univerio
univerio

Reputation: 20548

You can create/drop individual tables:

User.__table__.drop(engine)
User.__table__.create(engine)

Upvotes: 55

Related Questions