1

I am trying to use postgreSQL with SQLAlchemy. I having some issues because I am a new to SQLAlchemy, and may have misunderstood the documentation.

When I follow the documentation with SQLite I have no problems creating the database and the relations from the classes I specify. However, when I try to do it with Postgre I can't generate the relations or the db, instead I have to create the schemas and the tables manually in the shell.

This is what I currently have:

postgres_url = 'postgresql+psycopg2://some_user:some_password@localhost:5432/testdb'

engine = create_engine(postgres_url)

DB_session = sessionmaker(bind=engine)
db_session = DB_session()

Base = declarative_base()

Base.metadata.create_all(bind=engine)

#-----------------------------------------------------------
#                       User Entity
#-----------------------------------------------------------


class User(Base):

    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    fname = Column(String(45))
    lname = Column(String(45))
    token = Column(String(45))

    def __init__(self, fname, lname, token):
        self.fname = fname
        self.lname = lname
        self.token = token

    def __repr__(self):
        return 'Token: %s' % self.token

When I run the above code after manually creating the db I get a relation "users" does not exist, however, if I create the schema manually everything runs ok. I would appreciate a push in the right direction.

Chris Travers
  • 25,424
  • 6
  • 65
  • 182
lv10
  • 1,469
  • 7
  • 25
  • 46
  • 3
    Move the `Base.metadata.create_all()` line after your class. – Blender Mar 31 '13 at 07:09
  • @Blender Moving it after the class fixed the creating tables issue. However, unless I create the db manually (which is not a big deal, but at this point I'd like to know how to do it) the db is not being created. Do you have any suggestion in what I am missing in this? Thank you very much. – lv10 Mar 31 '13 at 07:18
  • There's no ORM-style syntax, but you can execute regular `CREATE DATABASE`: http://stackoverflow.com/questions/6506578/how-to-create-a-new-database-using-sqlalchemy – Blender Mar 31 '13 at 07:20
  • Thank you very much! I really appreciate it. Issue and questions solved. One last question: Are there styling recommendations as to how I should organize these in modules? – lv10 Mar 31 '13 at 07:26
  • Not that I know of, no. It really depends on what you're making. – Blender Mar 31 '13 at 07:34
  • I have a question related to this. I can't move this line after my class because this line is declared in __init__.py, while the class is declared in another file, therefore I don't have access to the engine variable in that file. Is there a clean way of running this method without importing in every model class file? – AgmLauncher Mar 15 '14 at 05:40

0 Answers0