SQLAlchemy, Declarative, PostgreSQL: cannot create tables

感情迁移 提交于 2021-02-20 04:04:14

问题


I created a number of classes I want to persist to the database. I would like to be able to run the app with a specific flag to take all those classes and create the corresponding tables in my db. To that end, I'm trying to import the classes and then call the Base.metadata.create_all(engine) method. However, that doesn't work. At the same time, when I call that from the file with each of those actual classes, the tables are created.

How do I go about the task of creating those tables? Should I try to create them from a single file/script, or do I add that line to each of those classes?

Here is an example of my code:

1) Item.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) main.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()

Sorry for the weird order of imports, but I read somewhere that the order of importing your classes and the Base matters, so I tried to play about with it.


回答1:


You already created Base in Item.py, just import it in main.py:

If main.py and Item.py are on the same folder, then in main.py:

from Item import Base, Item

And remove all imports inside main function, so main.py will look like:

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


来源:https://stackoverflow.com/questions/38205603/sqlalchemy-declarative-postgresql-cannot-create-tables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!