sopherapps / pydantic-redis

A simple Declarative ORM for Redis using pydantic Models
https://sopherapps.github.io/pydantic-redis
MIT License
39 stars 14 forks source link

dependent property cannot be `dict` #36

Closed wasperen2 closed 1 month ago

wasperen2 commented 2 months ago

Describe the bug When an attribute of a Model is a dict with another Model for values, retrieval fails with a pydantic_core._pydantic_core.ValidationError

To Reproduce The following code fails:

import uuid

from pydantic import Field
from pydantic_redis import Store, RedisConfig, Model

class Child(Model):
    _primary_key_field = "id"

    id: str = Field(
        default_factory=lambda: uuid.uuid4().hex,
    )
    name: str = Field()

class Parent(Model):
    _primary_key_field = "id"
    id: str = Field(
        default_factory=lambda: uuid.uuid4().hex,
    )
    name: str = Field()
    children: dict[str, Child] = Field(default_factory=dict)

store = Store(
    name="does_dict_work",
    redis_config=RedisConfig(host='localhost', port=6379, db=6)
)

store.register_model(Child)
store.register_model(Parent)

child1 = Child(name="bill bing")
child2 = Child(name="boom bing")
parent = Parent(name="bong bing", children={"one": child1, "two": child2})

Parent.insert(parent)

parents_retrieved = Parent.select(ids=[parent.id])
print(parents_retrieved)

with the following error:

pydantic_core._pydantic_core.ValidationError: 2 validation errors for Parent
children.one
  Input should be a valid dictionary or instance of Child [type=model_type, input_value='{"id":"62589e3d29c147299...d0","name":"bill bing"}', input_type=str]
    For further information visit https://errors.pydantic.dev/2.7/v/model_type
children.two
  Input should be a valid dictionary or instance of Child [type=model_type, input_value='{"id":"1585e3a8a9ae479c9...06","name":"boom bing"}', input_type=str]
    For further information visit https://errors.pydantic.dev/2.7/v/model_type

Expected behavior One would expect the Parent object is retrieved with it's children.