21

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:pass@01.02.03.04/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)
funnydman
  • 9,083
  • 4
  • 40
  • 55
alphanumeric
  • 17,967
  • 64
  • 244
  • 392
  • 5
    Why do you "have to" execute `drop_all` before `create_all`? If there are no other issues, `create_all` should be fine. And you can generally get interested in alembic and migrations. – Radosław Roszkowiak Jul 22 '17 at 22:38
  • [`MetaData.drop_all()`](http://docs.sqlalchemy.org/en/latest/core/metadata.html#sqlalchemy.schema.MetaData.drop_all) drops all tables stored in said metadata, not all in DB. – Ilja Everilä Jul 23 '17 at 20:33

3 Answers3

49

You can create/drop individual tables:

User.__table__.drop(engine)
User.__table__.create(engine)
univerio
  • 19,548
  • 3
  • 66
  • 68
1
from app import db
from models import User

User.__table__.create(db.engine)
User.__table__.drop(db.engine)
Shivansh Jagga
  • 1,541
  • 1
  • 15
  • 24
1

Another way to accomplish the task:

Base.metadata.tables['users'].create(engine)
Base.metadata.tables['users'].drop(engine)
Arnab De
  • 402
  • 4
  • 12