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

时间:2017-02-13 15:55:12

标签: 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)

我做错了什么?

1 个答案:

答案 0 :(得分:3)

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()