How to minimize type declarations? #912
-
Let's assume I have a "user" type (for example), which should used both to exchange data between certain services and also as schema to create the corresponding database table. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
If you're dealing with Pydantic classes, you could do something like: from piccolo.columns import Varchar
from piccolo.tables import Table
from piccolo.utils.pydantic import create_pydantic_model
class User(Table):
name = Varchar()
class UserModel(create_pydantic_model(User)):
def my_custom_method(self):
... So starting from the Piccolo table, and then creating the Pydantic model for exchanging data with other services. You can then add the validation to the Pydantic model. Creating Piccolo table instances from the Pydantic model should then be as simple as: piccolo_user_object = User(**UserModel.model_dump()) Likewise you can go from Piccolo table instances to Pydantic model instances: user = await User.objects().first()
user_model = UserModel(**user.to_dict()) Other than that, if you want the exact same methods on the Piccolo table and Pydantic model, you could use a mixin. |
Beta Was this translation helpful? Give feedback.
If you're dealing with Pydantic classes, you could do something like:
So starting from the Piccolo table, and then creating the Pydantic model for exchanging data with other services.
You can then add the validation to the Pydantic model. Creating Piccolo table instances from the Pydantic model should then be as simple as:
Likewise you can go from Piccolo table instances to Pydantic…