0

A follow up from How to delete a table in SQLAlchemy?

I want to drop a table User_test but when doing so I constantly get a NameError

I have defined the table with a python class called User.
Though I have forgotten how I defined its columns so I run the following User class and leave out the column definitions

engine = create_engine('postgresql+psycopg2://user:password@localhost/test')
Base = declarative_base(engine)

class User(Base):
   __tablename__ = 'User_test'
   __table_args__ = {'autoload':True}

But when I try to drop the User_test table (by trying out any of the following commands):

Base.metadata.drop_all(bind=engine, tables=[User_test.__table__])
Base.metadata.drop_all(tables=User_test)
User_test.drop(engine)
User_test.__table__.drop(engine)
User_test.__table__.drop(self._engine)

I get:

"Nameerror: name "User_test" is not defined"

Though when I run print(engine.table_names()) in python I can see the table.
And when running print(Base.metadata.tables.keys()) I see the table included

I also can see the table when querying the database through psql (ie running run \dt in psql)
Though when I try to run a select on the table in psql ie (Select * from User_test);

I get:

"Could not find a relationship with name User_test"

My questions are:

  • Why do I get a NameError when trying to drop the table in python and how can I fix it?
  • Why can I not perform a Select query on the table in psql when I clearly can see it?
  • Do I need to have the User class defined with all the Column names, is that why all this is happening?

Thank you

user12288003
  • 199
  • 1
  • 4
  • 14
  • 1
    The model is called `User` not `User_test` so `User.__table__.drop(engine)` looks to be the correct command as per the documentation: https://docs.sqlalchemy.org/en/13/core/metadata.html#creating-and-dropping-database-tables – SuperShoot Nov 03 '19 at 19:19
  • Thank you very much, I misread the documentation. But do you know why I can't access the table from psql? I.e I can see the table when running "\dt" but when I run "Select * from user_test" then I get an error, would you happen to have an idea why? thanks – user12288003 Nov 03 '19 at 19:31

0 Answers0