CodeBlanks Logo Icon CodeBlanks

Defining models

Learn to define models with declarative_base.

Defining models

In SQLAlchemy, models derive from a base class created by declarative_base(). Each model represents a database table; the __tablename__ attribute sets the table name.

from sqlalchemy.orm import declarative_base

Base = declarative_base()

class User(Base):
    __tablename__ = "users"
    id = Column(Integer, primary_key=True)
    name = Column(String)

The model class defines the table structure as a Python class. This lets you create tables without writing SQL.

The __tablename__ attribute

In each model class, the __tablename__ attribute sets the table name as a string. This is the name of the actual table in the database.

class Product(Base):
    __tablename__ = "products"
    # columns...

Table names are usually plural and lowercase (e.g. users, products). The model class is singular and starts with uppercase (e.g. User, Product).

Practice Define a User model

Start with from sqlalchemy import create_engine, Column, Integer, String and from sqlalchemy.orm import declarative_base. Define Base = declarative_base(). Inside class User(Base): add __tablename__ = "users". Add columns id = Column(Integer, primary_key=True) and name = Column(String). Print the table name with print(User.__tablename__).

Starter code

main.py
# bring in create_engine, Column, Integer, String from sqlalchemy
# bring in declarative_base
# define Base
# define User class (derive from Base, set table name to 'users')
# add id and name columns
# print User.__tablename__

Sample solution

main.py
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import declarative_base

Base = declarative_base()

class User(Base):
    __tablename__ = "users"
    id = Column(Integer, primary_key=True)
    name = Column(String)

print(User.__tablename__)

Expected output

users

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the model concepts

Term Meaning
declarative_base Gives the base class
__tablename__ Sets the table name
class User(Base) Defines a model
Column Creates a column

2 What does the __tablename__ attribute set?

  • The class name
  • The table name Correct answer
  • The connection string
  • The column type

Explanation: __tablename__ sets the name of the table in the database.

3 Complete the __tablename__ assignment

Question
class User(Base):
    ____ = "users"
Answer
class User(Base):
    __tablename__ = "users"

Explanation: The __tablename__ attribute sets the table name.

All lessons in Advanced