Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create a table in SQLAlchemy using Postgres?

Hi I'm trying to create a Table using SQLAlchemy in Postgres, it process all well but the table is not created in my Postgres server.

My models.py file:

 import sqlalchemy
 from sqlalchemy import Column, Integer, String
 from sqlalchemy import Table
 from sqlalchemy.ext.declarative import declarative_base

 Base = declarative_base()

 class MyTable(Base):
    __tablename__ = 'myTable'
    time_id = Column(String(), primary_key=True)
    customer_id = Column(String())
    inventory_id = Column(String())

    def toJSON(self):   
        json = {
           "time_id":self.alert_id,
           "customer_id":self.customer_id,
           "inventory_id":self.inventory_id,
       }
       return json

My creator file:

from sqlalchemy.ext.declarative import declarative_base
from models import MyTable
from sqlalchemy import create_engine

path="postgresql://postgres:password@localhost/test"
engine = create_engine(path, echo=True)
Base = declarative_base()
Base.metadata.create_all(engine)

What I am doing wrong?

like image 713
Joan Triay Avatar asked Mar 09 '23 21:03

Joan Triay


1 Answers

Base class is different for both file, you need to use the Base class which used for inheritance, so import your Base from models file:

#creatorfile
...
from models import Base

path="postgresql://postgres:password@localhost/test"
engine = create_engine(path, echo=True)
Base.metadata.create_all(engine)

Remove this line Base = declarative_base()

like image 104
metmirr Avatar answered Mar 13 '23 03:03

metmirr