Column types and constraints define what kind of data a database column can hold and rules it must follow. This helps keep data correct and organized.
Column types and constraints in Flask
Column(column_type, constraint1, constraint2, ...) Example: name = Column(String(50), nullable=False, unique=True)
Column type defines the kind of data (e.g., String, Integer, Date).
Constraints are rules like nullable=False (must have value) or unique=True (no duplicates).
id that is the primary key (unique identifier).id = Column(Integer, primary_key=True)email = Column(String(120), unique=True, nullable=False)
created_at = Column(DateTime, nullable=False)This Flask app defines a User table with columns using types and constraints. It creates the table, adds one user, and prints the user info.
from flask_sqlalchemy import SQLAlchemy from flask import Flask from datetime import datetime app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:' db = SQLAlchemy(app) class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(50), unique=True, nullable=False) email = db.Column(db.String(120), unique=True, nullable=False) joined_on = db.Column(db.DateTime, nullable=False, default=datetime.utcnow) with app.app_context(): db.create_all() user1 = User(username='alice', email='alice@example.com') db.session.add(user1) db.session.commit() print(f"User added: {user1.username}, Email: {user1.email}, Joined: {user1.joined_on}")
Use nullable=False to make sure a column always has data.
unique=True prevents duplicate values in a column.
Primary keys uniquely identify each row and are required for most tables.
Column types tell the database what kind of data to expect.
Constraints set rules to keep data valid and organized.
Using types and constraints helps avoid errors and keeps your data clean.
Practice
Solution
Step 1: Understand column types for text data
Text data of variable length is best stored using a string type that allows flexible length.Step 2: Match the correct SQLAlchemy type
db.Stringis designed for variable-length text, unlikedb.Integerordb.Boolean.Final Answer:
db.String -> Option AQuick Check:
Variable-length text = db.String [OK]
- Choosing db.Integer for text data
- Using db.Boolean for strings
- Confusing db.DateTime with text types
age in a Flask model?Solution
Step 1: Identify the correct type for age
Age should be stored as an integer, sodb.Integeris correct.Step 2: Set the nullable constraint
To make the column non-nullable, usenullable=False.Final Answer:
age = db.Column(db.Integer, nullable=False) -> Option DQuick Check:
Integer + non-nullable =age = db.Column(db.Integer, nullable=False)[OK]
- Setting nullable=True when non-null is needed
- Using wrong data type like String for age
- Confusing Boolean with Integer type
email = db.Column(db.String(120), unique=True, nullable=False)
What does the
unique=True constraint do?Solution
Step 1: Understand the unique constraint
Theunique=Trueconstraint ensures no two rows have the same value in this column.Step 2: Apply this to the email column
This means duplicate emails are not allowed, keeping each email distinct.Final Answer:
Prevents duplicate email values in the table -> Option AQuick Check:
unique=True means no duplicates [OK]
- Thinking unique=True allows duplicates
- Confusing unique with nullable
- Assuming unique changes data format
price = db.Column(db.String, nullable=False, unique='yes')
Solution
Step 1: Check the unique argument type
Theuniqueparameter expects a boolean value (TrueorFalse), not a string.Step 2: Identify the error in the code
Passingunique='yes'is invalid and will cause an error.Final Answer:
The unique argument should be a boolean, not a string -> Option BQuick Check:
unique must be True or False, not 'yes' [OK]
- Using string values for boolean parameters
- Thinking nullable and unique conflict
- Assuming price is reserved keyword
Solution
Step 1: Choose the correct type for phone numbers
Phone numbers often contain leading zeros, sodb.String(10)is better thandb.Integer.Step 2: Apply constraints for uniqueness and non-null
Useunique=Trueto prevent duplicates andnullable=Falseto disallow empty values.Final Answer:
phone = db.Column(db.String(10), unique=True, nullable=False) -> Option CQuick Check:
String(10) + unique + non-null =phone = db.Column(db.String(10), unique=True, nullable=False)[OK]
- Using Integer type losing leading zeros
- Allowing nullable=True when value is required
- Ignoring unique constraint for phone numbers
Ready to prove it?
Pass the test and this pattern moves unknown
