问题
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