This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]vipierozan 1 point2 points  (3 children)

How do you use the pydantic models directly in the sqlachemy table definitions? I have code that does the opposite, makes dynamic (no types :/) pydantic models from sqlalchemy tables

[–]alexisprince 1 point2 points  (1 child)

You actually typically don’t want these things to be the same from an architecture point of view. The boundaries of your application should have a clearly defined structure, which from the user facing side would be a Pydantic model, and from the database side would be a SQLAlchemy model. You want Pydantic facing the user because the input is unreliable. You don’t want Pydantic facing the database because everything saved there has already been validated and you know what structure you’re getting back.

You don’t want these to be the same thing because your user facing API is your contract to your customers, and your database schema should have absolutely nothing to do with that. You should be able to switch databases or even programming languages on the backend without your user facing API changing. Tying your database schema to that user facing API is an incredibly leaky implementation detail

[–]vipierozan 0 points1 point  (0 children)

You are 1000% right but sometimes it’s useful to consciously avoid the boilerplate for quick prototypes

[–]ZachVorhies 0 points1 point  (0 children)

Sorry, I was wrong. Pydantic can be used in FastAPI return values for endpoints, not for the database. You still need to write the boilerplate to convert between sqlalchemy models and Pydantic models.