FastAPI Backend Development Bootcamp · บทเรียน

พื้นฐาน ORM ของ SQLAlchemy

เริ่มต้นใช้งานตัวจับคู่เชิงวัตถุสัมพันธ์ (ORM) ของ SQLAlchemy เพื่อกำหนดโมเดลฐานข้อมูลและโต้ตอบกับฐานข้อมูลของคุณ

บทเรียน 1 จาก 411 ขั้นตอน

พื้นฐาน ORM ของ SQLAlchemy เป็นบทเรียน FastAPI Backend Development Bootcamp ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน FastAPI Backend Development Bootcamp และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส FastAPI Backend Development Bootcamp มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Bridging Code and Databases

Welcome to SQLAlchemy ORM! You'll learn how to connect your Python code to a database in a powerful, object-oriented way.

An Object Relational Mapper (ORM) is a tool that helps you interact with a database using objects from your programming language, instead of writing raw SQL.

  • It maps database tables to Python classes.
  • It maps database rows to Python objects.
  • It maps database columns to Python attributes.

This makes database operations feel more like working with regular Python objects.

Meet SQLAlchemy: Your ORM Tool

SQLAlchemy is a comprehensive and powerful ORM for Python. It provides a full suite of well-known persistence patterns for efficient and high-performing database access.

We'll focus on its ORM capabilities, which allow you to define your database structure (schema) using Python classes and interact with data using instances of those classes.

It supports many databases, including SQLite, PostgreSQL, MySQL, and more!

The Foundation: Declarative Base

To start defining our database models, we need a special base class. SQLAlchemy's Declarative Base provides this foundation.

It's essentially a factory that generates a base class which your ORM models will inherit from. This base class connects your Python classes to the underlying database tables.

Here's how you get it:

from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

Defining Your First Model

Once you have your Base, you can define your database tables as Python classes. Each class will represent a table, and its attributes will represent the columns.

Let's create a simple User model. It will have an id and a name.

from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

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

Model Attributes: Columns

In our User model, id and name are defined using Column objects. The Column function lets you specify details about each database column:

  • Data Type: Integer for whole numbers, String for text. SQLAlchemy has many more!
  • Primary Key: primary_key=True marks a column as the unique identifier for each row.
  • Length: String(50) sets a maximum length for text fields.
  • Nullable: By default, columns are nullable. You can set nullable=False to require a value.

The __tablename__ attribute is crucial; it tells SQLAlchemy the actual name of the table in your database.

Setting Up the Database Engine

Before we can create tables or interact with the database, SQLAlchemy needs to know where it is! This is where the Engine comes in.

An Engine is the starting point for any SQLAlchemy application. It connects your application to a specific database using a connection string.

For simplicity, we'll use an in-memory SQLite database, which is great for testing as it disappears when the program ends:

from sqlalchemy import create_engine

# Connect to an in-memory SQLite database
engine = create_engine('sqlite:///:memory:')

# For a file-based SQLite database:
# engine = create_engine('sqlite:///./test.db')

Creating Database Tables

With our Base, defined models, and engine, we can now create the actual database tables!

The Base.metadata.create_all(engine) method inspects all classes that inherit from Base and creates the corresponding tables in the database connected by the engine.

If the tables already exist, SQLAlchemy won't try to recreate them, preventing errors.

Full Example: Define & Create

Let's put it all together! Run this code to see how to define a model and create its table in an in-memory SQLite database.

Notice how we import everything needed, define Base, create our User model, set up the engine, and finally, create the tables.

from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base

# 1. Define the Base for ORM models
Base = declarative_base()

# 2. Define a Model (e.g., User table)
class User(Base):
    __tablename__ = 'users' # The actual table name in the database
    id = Column(Integer, primary_key=True) # Unique ID, automatically managed
    name = Column(String(50), nullable=False) # User's name, max 50 chars, required

    # A helpful representation for printing User objects
    def __repr__(self):
        return f"<User(id={self.id}, name='{self.name}')>"

# 3. Create a database engine
# Using an in-memory SQLite database for simplicity
engine = create_engine('sqlite:///:memory:')

# 4. Create all tables defined in Base
Base.metadata.create_all(engine)

print("Database tables created successfully!")
print("The 'users' table is now ready for data.")

Your Database Interaction Hub: The Session

Defining models and creating tables are just the first steps. To actually interact with the data (add, query, update, delete), you need a Session.

A Session is like a temporary workspace for your database operations. It holds all the objects you've loaded or created and keeps track of changes.

You create a Session using sessionmaker and bind it to your engine:

from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine

# (Assume 'engine' is already created as shown before)
engine = create_engine('sqlite:///:memory:')

# Create a Session factory
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

# To get a session:
# db = SessionLocal()
# try:
#     # Perform operations with db
#     pass
# finally:
#     db.close()

Quick Check: Model Setup

You've learned how to set up the basics of SQLAlchemy ORM. Let's test your understanding of the core components.

Recap: SQLAlchemy ORM Basics

Great job! You've taken your first steps into the world of SQLAlchemy ORM.

Here's what we covered:

  • What is an ORM: Maps Python objects to database tables.
  • SQLAlchemy: A powerful Python ORM.
  • Declarative Base: The foundation (Base = declarative_base()) for your models.
  • Defining Models: Creating Python classes (like User) that inherit from Base.
  • Columns: Using Column with data types (Integer, String) and attributes (primary_key).
  • Engine: Connecting to your database (create_engine).
  • Table Creation: Bringing models to life in the database (Base.metadata.create_all(engine)).
  • Session: Your workspace for database interactions (sessionmaker).

Next, we'll learn how to add, query, update, and delete data using these concepts!

เริ่มต้นได้ฟรี

เรียนรู้ FastAPI Backend Development Bootcamp ด้วย AI tutor — ฟรี

เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป

คอร์ส
21
บทเรียน
84

คำถามที่พบบ่อย

บทเรียน “พื้นฐาน ORM ของ SQLAlchemy” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “พื้นฐาน ORM ของ SQLAlchemy” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส FastAPI Backend Development Bootcamp ให้อัปเกรดเป็น CoddyKit PRO คอร์ส FastAPI Backend Development Bootcamp มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “พื้นฐาน ORM ของ SQLAlchemy”

เริ่มต้นใช้งานตัวจับคู่เชิงวัตถุสัมพันธ์ (ORM) ของ SQLAlchemy เพื่อกำหนดโมเดลฐานข้อมูลและโต้ตอบกับฐานข้อมูลของคุณ คุณปฏิบัติ FastAPI Backend Development Bootcamp ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน FastAPI Backend Development Bootcamp หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน FastAPI Backend Development Bootcamp บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน

บทเรียน “พื้นฐาน ORM ของ SQLAlchemy” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน FastAPI Backend Development Bootcamp นี้ได้ไหม

ได้ บทเรียน FastAPI Backend Development Bootcamp ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. พื้นฐาน ORM ของ SQLAlchemy
  2. การเชื่อมต่อ FastAPI กับ PostgreSQL
  3. การทำงาน CRUD ด้วย SQLAlchemy
  4. การย้ายฐานข้อมูลด้วย Alembic
← กลับไปที่ FastAPI Backend Development Bootcamp