PynamoDB
PynamoDB copied to clipboard
Programmatically define a table from Pydantic models
I would like to programmatically define the attributes of my model. Given a predefined entity in user.py:
import uuid
from pydantic import BaseModel
class User(BaseModel):
uuid: uuid.UUID
name: str
I would like to create my PynamoDB model as follows. PynamoDB-connector.py:
import uuid
from pynamodb.models import Model
from pynamodb.attributes import UnicodeAttribute
from user import User
type_map = {
str : UnicodeAttribute,
uuid.UUID : UnicodeAttribute
}
class UserModel(Model):
class Meta:
table_name = 'users'
#start of magic code
props = User.schema()['properties']
for p in props:
UserModel.magic_method_to_set_table_attributes_programmatically(p, type_map[props[p][type]](...))
#end of magic code
Is this, or something related to this, achievable? Thanks
It would be amazing to use a Pydantic Model directly mapped to DynamoDB. I think you can even change the title of you issue, to reference Pydantic.
I've tried to start a prof of concept for something like that, but ended just duplicating each Model.
@ikonst is this possible today ? To create a pynamodb model from a Pydantic schema ?
@ikonst May I pick this issue up to implement it? I'm working on a customization in my application related to Pydantic and PynamoDB mapping. Once I'm done, I can port to the repository. Let me know if it's necessary!
I think bringing this feature would be amazing. I am using pynamodb with pydantic right now but it's very cumbersome managing two sets of models and transforming them back and forth.
Not likely to make this library dependent on pydantic, but if you have a plan on how to make it an extra library, I can maybe advice.