[英]Generate schema SQL with SQLAlchemy
How does one generate the SQL/Migrate Code/Whatever with SQLAlchemy when using the Declarative Base? 使用声明式基础时,如何使用SQLAlchemy生成SQL /迁移代码/无论如何?
from sqlalchemy import *
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
engine = create_engine('mysql://root:password@localhost/mydb_dev', echo=True)
metadata = MetaData(bind=engine)
class User(Base):
__table__ = Table("users", metadata, autoload=True)
id = Column(Integer, primary_key=True)
display_name = Column(String)
email = Column(String)
password = Column(String)
def __repr__(self):
return "<User(id='{}', display_name='{}', email='{}')>".format(self.id, self.display_name, self.email)
class Site(Base):
__table__ = Table("sites", metadata, autoload=True)
id = Column(Integer, primary_key=True)
name = Column(String)
urls = relationship("URL")
def __repr__(self):
return "<Site(id='{}', name='{}')>".format(self.id, self.name)
I have this so far, I'd like to see what SQLAlchemy would generate as a schema. 到目前为止,我想要了解一下SQLAlchemy将作为模式生成的内容。
Or, does SQLAlchemy do this at all? 或者,SQLAlchemy完全可以做到这一点吗? Is this a case where I create and manage the database and it's schema separately, and I just update my entities to reflect it? 是在这种情况下,我分别创建和管理数据库及其架构,而只是更新实体以反映它吗?
Do understand that I am used to Doctrine2, and im very new to SQLAlchemy 确实了解我已经习惯了Doctrine2,并且对SQLAlchemy还是很陌生
Thanks! 谢谢!
You can create the db models by calling: 您可以通过调用以下命令来创建数据库模型:
metadata.create_all()
http://docs.sqlalchemy.org/en/latest/core/metadata.html#sqlalchemy.schema.MetaData.create_all http://docs.sqlalchemy.org/en/latest/core/metadata.html#sqlalchemy.schema.MetaData.create_all
Note that this only works for the creation of previously non-existent models, and doesn't handle updates or downgrades. 请注意,这仅适用于创建先前不存在的模型,并且不处理更新或降级。 Check out alembic for even finer control: 检查出Alembic以获得更好的控制:
http://alembic.zzzcomputing.com/en/latest/ http://alembic.zzzcomputing.com/en/latest/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.