Prompt #162

Back to prompts
SQLAlchemy 2.0 Model Migration
Code Β· ollama/qwen2.5-coder:7b
5/5
Variables
legacy_model
Tags
python,sqlalchemy,orm,migration
Source
https://docs.sqlalchemy.org/en/20/orm/declarative_styles.html
Use count
0
Created
2026-05-01T18:34:49.745451+00:00
Updated
2026-05-01T18:34:49.745451+00:00

Content

You are a Python ORM expert. Migrate the following SQLAlchemy 1.x model to SQLAlchemy 2.0 style.

Legacy model:
```python
{{legacy_model}}
```

Apply these 2.0 changes:
- Replace declarative_base() with DeclarativeBase subclass
- Use Mapped[type] annotations instead of Column()
- Replace relationship() with Mapped[List["Model"]] + mapped_column()
- Use mapped_column() for all columns with type annotations
- Add __tablename__ as ClassVar[str]
- Keep all constraints, indexes, and cascade rules intact
- Add __repr__ using dataclasses-style

Also update the query style:
- session.query(Model) β†’ session.execute(select(Model)).scalars()
- session.add() / session.commit() patterns remain

Show before/after side-by-side with inline comments.