python - SQLAlchemy,声明式,PostgreSQL : cannot create tables

标签 python postgresql sqlalchemy

我创建了一些我想保存到数据库的类。我希望能够使用特定标志运行应用程序以获取所有这些类并在我的数据库中创建相应的表。为此,我试图导入类,然后调用 Base.metadata.create_all(engine) 方法。但是,那是行不通的。同时,当我使用每个实际类从文件中调用它时,会创建表。

我该如何着手创建这些表格?我应该尝试从单个文件/脚本创建它们,还是将该行添加到每个类?

这是我的代码示例:

1) 项目.py

from sqlalchemy import Column, Integer, String, Float
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class Item(Base):
    __tablename__ = "items"

    id = Column(Integer, primary_key=True)
    name = Column(String)

    def __repr__(self):
        return "<~ {} ~> name: {}".format(self.id, self.name)

2) 主.py

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

def main():
    from sqlalchemy.ext.declarative import declarative_base
    Base = declarative_base()
    engine = create_engine('postgresql+psycopg2://me:my_passl@localhost/my_first_database', echo=True)
    from Item import Item
    print(Item)
    print(Item.__table__)
    Base.metadata.create_all(engine)

main()

对于奇怪的导入顺序感到抱歉,但我在某处读到导入类和 Base 的顺序很重要,所以我尝试使用它。

最佳答案

您已经在Item.py 中创建了Base,只需将其导入到main.py 中即可:

如果 main.pyItem.py 在同一个文件夹中,那么在 main.py 中:

从 Item import Base, Item

并删除 main 函数中的所有导入,因此 main.py 将如下所示:

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from Item import Base, Item

def main():
    engine = create_engine('postgresql+psycopg2://me:my_passl@localhost/my_first_database', echo=True)
    print(Item)
    print(Item.__table__)
    Base.metadata.create_all(engine)

main()

关于python - SQLAlchemy,声明式,PostgreSQL : cannot create tables,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38205603/

相关文章:

python - 将数据表拆分为许多小数据表 Python

SQL计数关联频率

postgresql - 如何在数字列中将字符串空格存储为 null

python - sqlalchemy 不创建我的外键

python - SQLAlchemy 中带有子句的递归 CTE

具有超过 20 个主题的 Python LDA Gensim 模型无法正确打印

python27 matplotlib : first and last element connected

postgresql - 当数据库连接关闭或丢失时, Hook Postgres 服务器运行代码?

Python3 SQLAlchemy 删除重复项

python-3.x - 使用 sqlalchemy 和 Oracle 时 db.session.commit() 出错