Models from Redis-OM are not recognized as BaseModel in Pydantic

494 views Asked by At

I am trying to use redis_om for my FastAPI cache but I get errors.

fastapi.exceptions.FastAPIError: Invalid args for response field! Hint: check that <class 'app.models.redis_models.Customer'> is a valid Pydantic field type. If you are using a return type annotation that is not a valid Pydantic field (e.g. Union[Response, dict, None]) you can disable generating the response model from the type annotation with the path operation decorator parameter response_model=None. Read more: https://fastapi.tiangolo.com/tutorial/response-model/

It says Customer is not a Pydantic model, but it should be.

Customer class I defined is a HashModel of aredis_om, HashModel is a RedisModel of aredis_om, and RedisModel is BaseModel of Pydantic.

class Customer(HashModel):

class HashModel(RedisModel, abc.ABC):

class RedisModel(BaseModel, abc.ABC, metaclass=ModelMeta):

But when I check if Customer is a subclass of BaseModel, it says it is not a subclass.

And it also said Hashmodel and RedisModel is not a BaseModel. Why does this happen and how to fix this problem?

code

from pydantic import EmailStr
import datetime
from typing import Optional

from pydantic import BaseModel
from aredis_om import HashModel, get_redis_connection, Migrator

from app.common.config import settings


redis_conn = get_redis_connection(url=settings.REDIS_DATA_URL, decode_responses=True)


class Customer(HashModel):
    first_name: str
    last_name: str
    email: EmailStr
    join_date: datetime.date
    age: int
    bio: Optional[str]

    class Meta:
        database = redis_conn


Migrator().run()

if __name__ == "__main__":
    if issubclass(Customer, BaseModel):
        print("Customer class is a subclass of BaseModel.")
    else:
        print("Customer class is NOT a subclass of BaseModel.")

result

Customer class is NOT a subclass of BaseModel.
pydantic-settings = "^2.0.3"
redis-om = "^0.2.1"
fastapi-cache2 = {extras = ["redis"], version = "^0.2.1"}
pydantic = "^2.0"

These are my dependencies.

1

There are 1 answers

0
MatsLindh On BEST ANSWER

aredis_om uses the BaseModel class from version 1 of Pydantic. This is provided as a separate class type from pydantic v2, and is what is being used aredis_om - so you're not checking for the correct class.

Check against BaseModel from the pydantic.v1 module instead (as shown in the linked compatibility layer:

from pydantic.version import VERSION as PYDANTIC_VERSION


PYDANTIC_V2 = PYDANTIC_VERSION.startswith("2.")

if PYDANTIC_V2:
    from pydantic.v1 import BaseModel, validator
...