-
Notifications
You must be signed in to change notification settings - Fork 1.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Unable to use Pure Pydantic Models as types for a rx.State
class
#4250
Comments
It seems like your example code is not complete, where is |
Hey @benedikt-bartscher
as shown in the dashboard example. The The route/page is also as shown by the dashboard example's table page
|
I'm also using Pydantic models in another part of my code base, but desire to use those models as |
Any success on your end? @riebecj .The idea is to avoid recreating dozens of models due to maintenance issues |
Ok, I had to do some hacky things to make it work, but it's possible. First, let me preface by saying you won't be able to use Pydantic models as front-end state attributes. They need to be back-end (so starting with a
To make it recognize a Pydantic if BaseModel not in serializers.SERIALIZERS:
@serializers.serializer
def serialize_pydantic(value: BaseModel) -> dict:
return value.model_dump(by_alias=True) Not sure if the serializer is actually called, but having one in the @functools.lru_cache
def custom_get_serializer(type_: type) -> Optional[serializers.Serializer]:
if issubclass(type_, BaseModel):
serializer = serializers.SERIALIZERS.get(BaseModel)
else:
serializer = serializers.SERIALIZERS.get(type_)
if serializer is not None:
return serializer
# If the type is not registered, check if it is a subclass of a registered type.
for registered_type, serializer in reversed(serializers.SERIALIZERS.items()):
if types._issubclass(type_, registered_type): # noqa: SLF001
return serializer
# If there is no serializer, return None.
return None
serializers.get_serializer = custom_get_serializer The only change being the addition of the class CustomModel(BaseModel):
foo: str = "bar"
class MyState(rx.State):
_custom_model = CustomModel()
@rx.var(cache=True)
def foo(self) -> str:
return self._custom_model.foo Then you can reference your Like I said: hacky, but it works. |
Bug Description: Unable to use a pure Pydantic model as a type for my runner state. The library throws the following error:
To Reproduce: Steps to reproduce the behavior:
Expected behavior: Expected to run the app after initialization.
Additional context: I have also tried the following approach, but the result is the same:
The
RunnerDetails
model cannot be modified to subclassrx.Model
orSQLModel
and must remain a pure Pydantic model because it is used in another part of the codebase that doesn't use thereflex
package.Help with solving this issue would be appreciated.
The text was updated successfully, but these errors were encountered: