当前位置: 代码迷 >> python >> 如何使用Postgres在SQLAlchemy中创建表?
  详细解决方案

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

热度:71   发布时间:2023-06-13 15:12:04.0

嗨我正在尝试使用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()

  相关解决方案