Handling table names with underscore ("_") in flask_sqlalchemy / Python

When you create table class using flask_sqlalchemy (the Flask extension for SQLAlchemy), it can maps the modal class to a proper table automatically. This is cool but if you have a table name with underscore (e.g. MY_SAMPLE_TABLE) and you name your model class with the underscore ('_') as usual, you will find SQLAlchemy will map your table name as something the following:

"MY__SAMPLE__TABLE"

Each single underscore (_) with becomes a double underscores (__). This is annoying and you might believe this is a bug, but in fact you can resolve this issues by naming your table class using the PEP8 naming convention, and named your class as:

class MySampleTable(db.Model):
     field_id = db.Column(db.Integer, primary_key = True)
     field_data = db.Column(db.String(200))

The the SQLAlchemy will map the MySampleTable class to table name as "MY_SAMPLE_TABLE" correctly.

For more information about PEP8, click here for details.

Comments

Popular posts from this blog