python - 如何使用 Postgres 在 SQLAlchemy 中创建表?

标签 python sql postgresql sqlalchemy postgresql-9.4

您好,我正在尝试在 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/

相关文章:

python - 无法在 jupyter notebook 中导入模块;错误的系统路径

python - 将 Python 函数范围限制为仅局部变量

mysql - 如何获取子查询组中最近的 n 个条目?

sql - 从每组的第一行和最后一行获取数据

sql - PostgreSQL SQL : Find single arbitrary tuple from each id

python - fnv 0.2.0 使用类型错误

Python open ("x", "r") 函数,我怎么知道或控制文件应该有哪种编码?

SQL - 将同一个表中的两个字段连接到另一个表中的单个字段

PostgreSQL 和 JDBC 准备语句缓存

ruby-on-rails - PGError : ERROR: current transaction is aborted