codemation / pydbantic

A single model for shaping, creating, accessing, storing data within a Database
https://pydbantic.readthedocs.io/en/latest/
Apache License 2.0
228 stars 15 forks source link

Issue with standard primary keys #59

Closed rmlopes closed 1 year ago

rmlopes commented 1 year ago

Hi,

I have two models:

class ModelA:
    name: str = PrimaryKey()

class ModelB:
    name: str = PrimaryKey()
    other : ModelA

When I try to create a ModelB I get a pydantic error:

    _instance = ModelB(name="uniquename", other="existing_modelA_object_name")

    # output: 
    # pydantic.error_wrappers.ValidationError: 1 validation error for ModelB
    # other
    #    value is not a valid dict (type=type_error.dict)

I am sure I am missing something, but I don't know what...

codemation commented 1 year ago

Hi @rmlopes , the error is nearly pointing you in the right direction.

When you create an instance of ModelB with the above definitions, you need to pass something like this:

_instance = ModelB(name="uniquename", other=ModelA(name="existing_modelA_object_name"))

Or if existing you can get the instance first

model_a_instance = await ModelA.get(name="existing_modelA_object_name")
_instance = ModelB(name="uniquename", other=model_a_instance)

Or as the error describes, use a dict that would also correctly instantiate ModelA

_instance = ModelB(name="uniquename", other={"name": "existing_modelA_object_name"})
rmlopes commented 1 year ago

Thanks @codemation. Is this covered in the docs (I couldn't find it)?

I was assuming that something like the dict approach would happen under the hood :) (I should have checked the source)

codemation commented 1 year ago

@rmlopes i think there are less examples in docs about instantiating objects with related DataBaseModel objects, but the error and behavior I am describing is inherited from pydantic not explicitly pydbantic. pydbantic will follow most of the same rules related to model instance creation & validation as pydantic, the behavior for querying & storing these related models is where pydbantic comes in.