Loading

Quipoin Menu

Learn • Practice • Grow

flask / Defining Models
tutorial

Defining Models

Models are Python classes that represent database tables. Each attribute of the class represents a column. SQLAlchemy translates your Python code into SQL.

Example: User Model

class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(20), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
password = db.Column(db.String(60), nullable=False)

def __repr__(self):
return f"User('{self.username}', '{self.email}')"

Common Column Types

  • db.Integer – whole numbers.
  • db.String(length) – text with max length.
  • db.Text – long text (no max).
  • db.DateTime – date and time.
  • db.Boolean – True/False.

Column Constraints

  • primary_key=True – unique identifier for each row.
  • unique=True – no duplicate values in this column.
  • nullable=False – column cannot be empty.
  • default=value – default value if not provided.

Adding Models to Database

After defining your model, run `db.create_all()` again to add the new table.


Two Minute Drill
  • Each model class maps to a database table.
  • Each attribute (db.Column) maps to a table column.
  • Primary key, unique, nullable are common constraints.
  • Use `__repr__` to display object info for debugging.

Need more clarification?

Drop us an email at career@quipoinfotech.com