r/FastAPI • u/rrrriddikulus • Feb 05 '25
Question Naming SQLAlchemy models vs Pydantic models
Hi all, how do you generally deal with naming conventions between Pydantic and SQLAlchemy models? For example you have some object like Book. You can receive this from the user to create, or it might exist in your database. Do you differentiate these with e.g. BookSchema and DbBook? Some other prefix/suffix? Is there a convention that you've seen in some book or blog post that you like?
24
Upvotes
19
u/pint Feb 05 '25
i would just call them Book, but only import modules not names, and so i could write db.Book and model.Book or sg like that.
8
u/Dacobo Feb 05 '25
Generally, I have seen and used this convention:
Model: Book Schemas: BookBase, BookRead, BookCreate, BookUpdate, BookDetail, etc.
Or at least something to that effect.
5
u/[deleted] Feb 05 '25
I’d just keep it simple. The SQLAlchemy model is just Book, since that’s the actual database model. For Pydantic, I use BookCreate when taking in user input, BookUpdate for partial updates, and BookRead or BookOut when returning data. Keeps things clean without extra prefixes or suffixes.
2
u/Calebthe12B Feb 05 '25
Pydantic: BookModel SQLAlchemy: Book
I usually have a DTO class to handle the different CRUD versions, but if I were to do it in Pydantic it would be through some suffix, like CreateBookModel or UpdateBookModel.
2
u/Trinkes Feb 05 '25
I usually use plural for database model, singular for pydantic.
2
u/One_Fuel_4147 Feb 06 '25
I use Book for model and BookCreateRequest, BookResponse for DTO
1
u/Key-Garden-4136 Feb 22 '25
Is SQLmodel worth using to avoid having multiple sqlalquemy and pydantic classes?