PynamoDB icon indicating copy to clipboard operation
PynamoDB copied to clipboard

Programmatically define a table from Pydantic models

Open Pedrozena opened this issue 3 years ago • 5 comments

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

Pedrozena avatar Apr 12 '21 17:04 Pedrozena

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.

lopesjeronimo avatar May 20 '21 19:05 lopesjeronimo

@ikonst is this possible today ? To create a pynamodb model from a Pydantic schema ?

a-dragos avatar Jul 27 '23 23:07 a-dragos

@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!

ngdangdat avatar Nov 08 '23 06:11 ngdangdat

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.

oesah avatar Dec 12 '23 00:12 oesah

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.

ikonst avatar Dec 12 '23 02:12 ikonst