To include Pydantic models in your CRUD operations, particularly for converting SQLAlchemy objects to Pydantic schemas, you'll want to leverage the pydantic library to effectively serialize your SQLAlchemy models. Pydantic provides facilities for data validation and serialization, making it ideal for such tasks.
Installing Pydantic
First, ensure Pydantic is installed:
pip install pydantic
Implementation
Here's how you can modify the CRUD class to convert SQLAlchemy models to Pydantic schemas in the get method. I'll also set up a simple conversion function that takes a Pydantic schema type as an argument.
import asyncio
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import sessionmaker, selectinload
from sqlalchemy.future import select
from sqlalchemy.exc import SQLAlchemyError
from typing import Type, TypeVar, Optional, Any
from pydantic import BaseModel
# Example model import goes here
# from your_existing_models_import import MyModel, RelatedModel
# Example pydantic schema
# from your_schema_import import MyModelSchema
DATABASE_URL = "postgresql+asyncpg://user:password@localhost/dbname"
# Async engine and session setup
engine = create_async_engine(DATABASE_URL, echo=True, future=True)
AsyncSessionLocal = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
# Type variable for a Pydantic model
T = TypeVar('T', bound=BaseModel)
class AsyncCRUDBase:
def __init__(self, model):
"""
Async CRUD object with default methods to Create, Read, Update, Delete (CRUD).
:param model: A SQLAlchemy model class
"""
self.model = model
async def get(self, db: AsyncSession, filters: dict, schema_output: Optional[Type[T]] = None) -> Optional[Any]:
"""
Get a single record using filters on model fields and relations, optionally converting to a Pydantic model.
:param filters: A dictionary where keys can be attributes of the main model or
attributes of the related models, using dot notation for relations.
E.g., {'name': 'Example', 'related_model.related_field': 'Some Value'}
:param schema_output: Optional Pydantic schema class for output conversion.
"""
try:
query = select(self.model)
relationships = {}
# Parse filters for direct attributes and relationships
for attr, value in filters.items():
if '.' in attr:
# It's a relationship field
rel_attr, rel_field = attr.split('.', 1)
if rel_attr not in relationships:
relationships[rel_attr] = {}
relationships[rel_attr][rel_field] = value
else:
# It's a direct attribute of the model
query = query.filter(getattr(self.model, attr) == value)
# Use selectinload for any relationship filters
for rel_attr, rel_filter in relationships.items():
relation = getattr(self.model, rel_attr)
query = query.options(selectinload(relation))
for attr, value in rel_filter.items():
query = query.filter(getattr(relation.property.mapper.class_, attr) == value)
result = await db.execute(query)
record = result.scalars().first()
if schema_output and record:
return schema_output.from_orm(record)
return record
except SQLAlchemyError as e:
print(f"Error retrieving record with filters: {e}")
return None
async def get_all(self, db: AsyncSession, skip: int = 0, limit: int = 100) -> list:
"""Get all records, with optional pagination."""
try:
result = await db.execute(select(self.model).offset(skip).limit(limit))
return result.scalars().all()
except SQLAlchemyError as e:
print(f"Error retrieving records: {e}")
return []
async def create(self, db: AsyncSession, obj_in) -> Optional[Any]:
"""Create a new record."""
try:
db.add(obj_in)
await db.commit()
await db.refresh(obj_in)
return obj_in
except SQLAlchemyError as e:
await db.rollback()
print(f"Error creating record: {e}")
return None
async def update(self, db: AsyncSession, filters: dict, update_data: dict) -> Optional[Any]:
"""
Update an existing record with dynamic filters on both model and relations.
:param filters: A dictionary where keys can be attributes of the main model or
attributes of the related models, using dot notation for relations.
E.g., {'name': 'Old Name', 'related_model.related_field': 'Some Value'}
:param update_data: A dictionary of attributes to update on the main model.
"""
try:
query = select(self.model)
relationships = {}
# Parse filters for direct attributes and relationships
for attr, value in filters.items():
if '.' in attr:
# It's a relationship field
rel_attr, rel_field = attr.split('.', 1)
if rel_attr not in relationships:
relationships[rel_attr] = {}
relationships[rel_attr][rel_field] = value
else:
# It's a direct attribute of the model
query = query.filter(getattr(self.model, attr) == value)
# Use selectinload for any relationship filters
for rel_attr, rel_filter in relationships.items():
relation = getattr(self.model, rel_attr)
query = query.options(selectinload(relation))
for attr, value in rel_filter.items():
query = query.filter(getattr(relation.property.mapper.class_, attr) == value)
result = await db.execute(query)
db_obj = result.scalars().first()
if not db_obj:
return None
# Update fields of the main object
for key, value in update_data.items():
if hasattr(db_obj, key):
setattr(db_obj, key, value)
await db.commit()
await db.refresh(db_obj)
return db_obj
except SQLAlchemyError as e:
await db.rollback()
print(f"Error updating record: {e}")
return None
async def delete(self, db: AsyncSession, id: int) -> Optional[Any]:
"""Delete a record."""
try:
result = await db.execute(select(self.model).filter(self.model.id == id))
db_obj = result.scalars().first()
if not db_obj:
return None
await db.delete(db_obj)
await db.commit()
return db_obj
except SQLAlchemyError as e:
await db.rollback()
print(f"Error deleting record: {e}")
return None
# Example Pydantic schema for MyModel
class MyModelSchema(BaseModel):
id: int
name: str
# Add other fields and relations here
class Config:
orm_mode = True
# Example usage of async CRUD operations
async def main():
async with AsyncSessionLocal() as session:
crud = AsyncCRUDBase(MyModel)
# Example get operation using filters in model and relations
filters = {'name': 'Example Name', 'related_model.related_field': 'Some Value'}
record = await crud.get(session, filters, schema_output=MyModelSchema)
print(record.json() if record else "No record found")
if __name__ == "__main__":
asyncio.run(main())
Key Components:
-
Pydantic Model: Define a Pydantic model (MyModelSchema) with orm_mode=True to facilitate the conversion from SQLAlchemy model instances to Pydantic model instances. This allows Pydantic to use the ORM's instance methods and properties for validation and serialization.
-
Generic Conversion: The get method now optionally accepts a Pydantic schema (schema_output). If provided, it converts the retrieved SQLAlchemy object to a Pydantic model using from_orm.
-
Optional JSON Output: You can easily convert the resulting Pydantic model to a JSON string using .json() for serialization to APIs or other layers.
This solution gives you a flexible way to integrate SQLAlchemy and Pydantic, facilitating the creation of fast APIs and data processing layers.