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.

6
  • 3
    Move the Base.metadata.create_all() line after your class. Commented Mar 31, 2013 at 7: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. Commented Mar 31, 2013 at 7:18
  • There's no ORM-style syntax, but you can execute regular CREATE DATABASE: stackoverflow.com/questions/6506578/… Commented Mar 31, 2013 at 7: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? Commented Mar 31, 2013 at 7:26
  • Not that I know of, no. It really depends on what you're making. Commented Mar 31, 2013 at 7:34

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.