[英]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.要创建User
表,我必须使用drop_all
和create_all
方法。 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?我想知道是否有一种方法可以在不删除(或删除)数据库中任何现有表的情况下创建User
表?
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)
You can create/drop individual tables :您可以创建/删除单个表:
User.__table__.drop(engine)
User.__table__.create(engine)
from app import db
from models import User
User.__table__.create(db.engine)
User.__table__.drop(db.engine)
Another way to accomplish the task:完成任务的另一种方法:
Base.metadata.tables['users'].create(engine)
Base.metadata.tables['users'].drop(engine)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.