DEV Community

Muhammad Atif Iqbal
Muhammad Atif Iqbal

Posted on

2 2 2 2 1

Is '__tablename__' Compulsory in SQLAlchemy? Can We Change It?

πŸ“Œ 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).


READ complete article on this

βœ… 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)
Enter fullscreen mode Exit fullscreen mode
  • 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)
Enter fullscreen mode Exit fullscreen mode

πŸ’‘ 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)
Enter fullscreen mode Exit fullscreen mode

πŸ’‘ 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)