Serialize relationship in SQLModel

Abstract: Resolve infinite recursion and data exposure when serializing SQLModel relationships by using separate Pydantic read schemas.

Created: 2026-10-25 by

To serialize relationships in SQLModel with FastAPI, define separate Pydantic models for reading data that include the desired nested fields, while keeping database-only models distinct. Use model_validate to convert ORM instances into these read schemas, ensuring circular references are handled gracefully and only relevant data is exposed to the API client.

Understanding the Model Separation Strategy

SQLModel is built on top of SQLAlchemy and Pydantic, which creates a natural separation between how data is stored in the database and how it is transmitted over the network. The core challenge arises when you have relationships, such as a one-to-many or many-to-one connection between two tables. If you attempt to serialize your primary SQLModel directly, you may encounter infinite recursion errors if the relationship loops back to itself, or you might expose sensitive internal data that should remain hidden from the API consumer. The standard solution is to adopt a layered architecture where you maintain distinct model definitions for different contexts. You typically need three types of models:
  • Database Models: These inherit from SQLModel and define the table structure, columns, and relationships using SQLAlchemy constructs like relationship(). They are used exclusively for database operations like querying and inserting.
  • Create/Update Schemas: These inherit from Pydantic (or SQLModel depending on preference) and define what data a client must provide when creating or updating an entity. They usually exclude auto-generated fields like IDs and timestamps.
  • Read Schemas: These inherit from Pydantic and define the exact structure of the JSON response sent to the client. This is where you explicitly include related objects to control serialization depth.
This separation ensures that your database schema can evolve independently of your API contract. It also prevents accidental exposure of internal implementation details. For instance, you might have a complex join table that is necessary for your database integrity but irrelevant to the frontend application. By using separate read schemas, you can completely omit those fields without modifying the underlying database model.

Defining the Database and Read Models

Let us consider a practical example involving a User and a Post. A user can have many posts, establishing a one-to-many relationship. In your database model, you would define this using the back_populates attribute to ensure bidirectional access.
from sqlmodel import SQLModel, Field, Relationship
from typing import List, Optional
from datetime import datetime

class User(SQLModel, table=True):
    id: Optional[int] = Field(default=None, primary_key=True)
    name: str
    email: str
    created_at: datetime = Field(default_factory=datetime.utcnow)
    
    # Relationship definition
    posts: List["Post"] = Relationship(back_populates="owner")

class Post(SQLModel, table=True):
    id: Optional[int] = Field(default=None, primary_key=True)
    title: str
    content: str
    owner_id: int = Field(foreign_key="user.id")
    
    owner: Optional[User] = Relationship(back_populates="posts")
Notice that the User class includes a list of Post objects. If you were to return a User instance directly from a FastAPI endpoint, Pydantic would attempt to serialize all associated posts. If those posts had their own relationships, the serialization could become deeply nested or fail entirely due to circular dependencies. To solve this, you create specific Pydantic schemas for reading data. These schemas do not inherit from SQLModel or table=True; they are purely for data validation and serialization.
from pydantic import BaseModel

class PostBase(BaseModel):
    title: str
    content: str

class PostRead(PostBase):
    id: int
    owner_id: int
    
    class Config:
        from_attributes = True

class UserRead(BaseModel):
    id: int
    name: str
    email: str
    created_at: datetime
    posts: List[PostRead] = []
    
    class Config:
        from_attributes = True
By defining PostRead separately, you have full control over which fields are included. You can choose to exclude owner_id if the frontend does not need it, or you can add computed fields that are derived from other data. The from_attributes = True setting (formerly orm_mode) tells Pydantic to extract values from Python objects rather than expecting a dictionary, which is crucial when working with ORM instances.

Serializing Data in FastAPI Endpoints

Once your models and schemas are defined, the next step is to implement the FastAPI endpoints. When you query the database using SQLModel's session, you receive instances of your database models (User and Post). You cannot pass these directly to the response because they contain SQLAlchemy-specific attributes and potentially unserializable data structures. Instead, you must convert them into your read schemas. The most efficient way to do this is using the model_validate method available in Pydantic V2 and compatible SQLModel versions. This method takes an ORM object and returns a validated Pydantic model instance.
from fastapi import FastAPI, Depends
from sqlmodel import Session, select

app = FastAPI()

def get_session():
    # Setup your database session here
    with Session(engine) as session:
        yield session

@app.get("/users/{user_id}", response_model=UserRead)
def read_user(user_id: int, session: Session = Depends(get_session)):
    user = session.get(User, user_id)
    if not user:
        raise HTTPException(status_code=404, detail="User not found")
    
    # Convert ORM instance to Pydantic read schema
    return UserRead.model_validate(user)
When UserRead.model_validate(user) is called, Pydantic inspects the User instance. It finds the posts attribute, which is a list of Post ORM objects. Because PostRead is specified in the UserRead schema, Pydantic automatically validates and converts each post in the list. This recursive validation handles the relationship serialization seamlessly. It is important to note that if you have large datasets, loading all relationships eagerly can impact performance. In such cases, you might want to limit the number of related items loaded in the database query itself before serialization. You can use SQLAlchemy's joinedload or selectinload within your SQLModel query to optimize this process. However, for typical CRUD applications, the automatic conversion provided by model_validate is sufficient and keeps the code clean. If you encounter issues with circular references where User points to Post and Post points back to User, you can use Optional` types or exclude fields in the read schema to break the cycle. For more complex scenarios involving computed fields that should not be persisted, refer to guides on excluding computed fields from Pydantic dumps.

Handling Nested Relationships Deeply

For deeper nesting, such as users having posts which have comments, you simply extend the read schemas. Define a CommentRead schema, include it in PostRead, and include PostRead in UserRead. The from_attributes configuration ensures that Pydantic correctly traverses the object graph. Always ensure that your database queries load the necessary relationships; otherwise, accessing lazy-loaded attributes during serialization might trigger additional database queries, leading to the N+1 problem. Using eager loading strategies in your SQLModel query is the best practice to mitigate this performance bottleneck.

Frequently Asked Questions

Why do I get a circular reference error when serializing?

Circular reference errors occur when Object A references Object B, and Object B references Object A, causing infinite recursion during JSON encoding. To fix this, ensure your read schemas do not include bidirectional links, or use Optional types and carefully structure your nested schemas to break the loop at the API level.

Can I use the same model for database and API responses?

While technically possible with careful configuration, it is strongly discouraged. Mixing database models with API response schemas exposes internal implementation details and makes it difficult to handle validation rules specific to input versus output. Separating them provides better security, flexibility, and clearer code maintenance.

How do I handle many-to-many relationships in serialization?

Many-to-many relationships often involve a junction table. In your read schema, you can choose to expose the raw list of related IDs or the full related objects. If you expose full objects, ensure you define appropriate read schemas for the related entities and use model_validate on the collection to transform the ORM results efficiently.

What is the difference between model_validate and dict()?

model_validate performs strict type checking and validation against the Pydantic schema, ensuring data integrity before serialization. Using dict() simply converts the object to a dictionary without validation, which can lead to unexpected data types or missing fields in your JSON response if the ORM object structure changes.

How can I optimize performance for deep nested relationships?

To optimize performance, use SQLAlchemy's eager loading options like joinedload or selectinload in your database queries. This fetches all related data in fewer queries, preventing the N+1 query problem. Additionally, consider limiting the depth of nested relationships in your API to reduce payload size and processing time.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More