π Is __tablename__
Compulsory in SQLAlchemy? Can We Change It?
No, __tablename__
is not compulsory, but it is highly recommended in SQLAlchemy when using the ORM (Object-Relational Mapping).
β
What Does __tablename__
Do?
When you define a model in SQLAlchemy like this:
class User(Base):
__tablename__ = "users" # β
Defines the table name
id = Column(Integer, primary_key=True, index=True)
email = Column(String, unique=True, index=True, nullable=False)
hashed_password = Column(String, nullable=False)
- The
__tablename__
sets the name of the table in the database. - Without it, SQLAlchemy will automatically generate a table name based on the class name.
β
What Happens If We Don't Use __tablename__
?
If you donβt define __tablename__
, SQLAlchemy will autogenerate a name based on the class.
Example Without __tablename__
:
class User(Base):
id = Column(Integer, primary_key=True, index=True)
email = Column(String, unique=True, index=True, nullable=False)
hashed_password = Column(String, nullable=False)
π‘ Generated Table Name: "user"
(lowercase version of the class name)
β
Can We Change __tablename__
?
Yes! You can change it to any valid table name.
Example with a Custom Table Name:
class User(Base):
__tablename__ = "my_custom_users_table" # β
Custom table name
id = Column(Integer, primary_key=True, index=True)
email = Column(String, unique=True, index=True, nullable=False)
hashed_password = Column(String, nullable=False)
π‘ Now the table name will be: my_custom_users_table
β
When Should We Use __tablename__
?
Scenario | Should You Use __tablename__ ? |
---|---|
You want full control over table names | β Yes |
You follow strict database naming rules | β Yes |
You are fine with autogenerated names | β No (optional) |
β Final Answer:
__tablename__
is not required, but recommended.- You can change the table name to anything valid.
- If you donβt define it, SQLAlchemy will use the lowercase class name as the table name.
Top comments (0)