Home > Enterprise >  Flask SQLAlchemy does not create all the columns of my model
Flask SQLAlchemy does not create all the columns of my model

Time:11-22

I am using flask and flask SQLAlchemy to create my sqllite database that has one table with several columns. I have created my model but once I run the app it only creates the first 03 columns ?!!!

...

db = SQLAlchemy()

def setup_db(app):
    db.app = app
    db.init_app(app)

def db_drop_and_create_all():
    db.drop_all()
    db.create_all()

...

@dataclass
class ChurnModel(inheritedModels):
    id = int
    customerID = String
    gender = String
    SeniorCitizen: int
    Partner: String
    ...

    __tablename__ = 'churn'

    id = Column(Integer().with_variant(Integer, "sqlite"), primary_key=True)
    customerID = Column(String(255), nullable=False)
    gender = Column(String(255))
    SeniorCitizen: Column(Integer())
    Partner: Column(String(255))
    ...

    def get_churn(self):
        return {
            "id": self.id,
            "customerID": self.customerID,
            "gender": self.gender,
            "SeniorCitizen": self.SeniorCitizen,
            "Partner": self.Partner,
            ...
        }

    ...

This is what I have found in the database.db file surrounded by a lot of nulls:


TE TABLE churn (
    id INTEGER NOT NULL, 
    "customerID" VARCHAR(255) NOT NULL, 
    gender VARCHAR(255), 
    PRIMARY KEY (id)
)

Any explanation?!

CodePudding user response:

After looking at the code, I think this is an expected behaviour since the only columns you defined are id, customerID, and gender. Maybe you just got confused on how to use type hints, or you didn't pay attention to that, that's all.

Try this instead :

@dataclass
class ChurnModel(inheritedModels):
    id: int
    customerID: String
    gender: String
    SeniorCitizen: int
    Partner: String
    ...

    __tablename__ = 'churn'

    id = Column(Integer().with_variant(Integer, "sqlite"), primary_key=True)
    customerID = Column(String(255), nullable=False)
    gender = Column(String(255))
    SeniorCitizen= Column(Integer())
    Partner= Column(String(255))
    ...


  • Related