【问题标题】:how to create a table in SQLAlchemy using Postgres?如何使用 Postgres 在 SQLAlchemy 中创建表?
【发布时间】:2017-02-13 15:55:11
【问题描述】:

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

我做错了什么?

【问题讨论】:

    标签: python sql postgresql sqlalchemy postgresql-9.4


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2013-03-24
      • 2021-05-25
      • 2015-05-04
      • 2022-01-15
      • 2023-02-02
      • 1970-01-01
      • 2021-12-21
      • 1970-01-01
      • 2020-05-12
      相关资源
      最近更新 更多