您好,我正在尝试在 Postgres 中使用 SQLAlchemy 创建一个表,它处理得很好,但该表不是在我的 Postgres 服务器中创建的。
我的 models.py 文件:
import sqlalchemy
from sqlalchemy import Column, Integer, String
from sqlalchemy import Table
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class MyTable(Base):
__tablename__ = 'myTable'
time_id = Column(String(), primary_key=True)
customer_id = Column(String())
inventory_id = Column(String())
def toJSON(self):
json = {
"time_id":self.alert_id,
"customer_id":self.customer_id,
"inventory_id":self.inventory_id,
}
return json
我的创作者文件:
from sqlalchemy.ext.declarative import declarative_base
from models import MyTable
from sqlalchemy import create_engine
path="postgresql://postgres:password@localhost/test"
engine = create_engine(path, echo=True)
Base = declarative_base()
Base.metadata.create_all(engine)
我做错了什么?
最佳答案
Base
类对于两个文件是不同的,你需要使用用于继承的 Base
类,所以从模型中导入你的 Base
文件:
#creatorfile
...
from models import Base
path="postgresql://postgres:password@localhost/test"
engine = create_engine(path, echo=True)
Base.metadata.create_all(engine)
删除这一行 Base = declarative_base()
关于python - 如何使用 Postgres 在 SQLAlchemy 中创建表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42208207/