Python
Column and type
Learn column types with Column(Integer), Column(String).
Column and types
Column defines a table column. It takes a type as its first parameter: Integer, String, Float, Boolean, DateTime and so on.
class Product(Base):
__tablename__ = "products"
id = Column(Integer, primary_key=True)
name = Column(String)
price = Column(Float)
in_stock = Column(Boolean)
primary_key=True marks a primary key, nullable=False marks a non-null column. A length can be given as in String(50).
Meaning of types
Each column type maps to a corresponding type in the database. Integer stores integers, String stores text, Float stores decimals, Boolean stores true/false.
amount = Column(Integer) # integer
label = Column(String(50)) # text up to 50 chars
ratio = Column(Float) # decimal
active = Column(Boolean) # true/false
Choosing the right type matters for validation and efficiency. A wrong type can cause data loss.
Exercise Define a Product model
Start with from sqlalchemy import create_engine, Column, Integer, String, Float and from sqlalchemy.orm import declarative_base. Define Base = declarative_base(). Inside class Product(Base): add __tablename__ = "products". Add columns id = Column(Integer, primary_key=True), name = Column(String) and price = Column(Float). Print the table name with print(Product.__tablename__).
Show example solution
from sqlalchemy import create_engine, Column, Integer, String, Float
from sqlalchemy.orm import declarative_base
Base = declarative_base()
class Product(Base):
__tablename__ = "products"
id = Column(Integer, primary_key=True)
name = Column(String)
price = Column(Float)
print(Product.__tablename__)
Test yourself
-
What does Column(Integer, primary_key=True) specify?
- An auto-increment column
- A foreign key column
- A nullable column
- A primary key column
Show answer
A primary key column — primary_key=True marks the column as a primary key.
-
Complete the String column definition
class Product(Base):
__tablename__ = "products"
name = Column(____)
Show answer
class Product(Base):
__tablename__ = "products"
name = Column(String)
-
Match the type concepts
- Integer
- Stores integers
- String
- Stores text
- Float
- Stores decimals
- Boolean
- Stores true/false
Next lesson: Query