-
|
I have recently switched to Postgresql from MySQL and have come across an anomaly. In MySQL I could fetch this from Database and it would be cast into Pydantic schema automatically. However when using Postgres this conversion doesn't seem to happen. For The device object is in this case a Record object Why would FastAPI's behaviour change only because a different database is used? I can't find anything in the documentation about this. UPDATE This is quite odd that it doesn't happen automatically. I have to change code because the underlying database has changed. The worse part is that when no record has been found, the cast will crash. Hence I have to make more repetitive changes: Any advise please? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
|
Hi @houmie - I'm not sure why you think fastapi does automatic casting within your code, it definitely doesn't. The only situation it does "casting" is when you return a model from an endpoint with a schema defined |
Beta Was this translation helpful? Give feedback.
-
|
Hi Mause, Thank you for your reply. This is caused by the underlying postgres library being used. I'm guessing there is some magic going on in the Record object of asyncpg. My guess is that the returned Record from the library does not expose the properties. Thus it requires to manually select the attributes to be fed into the pydantic model. The function I provided above does the casting automatically when aiomysql is used (MySQL is the underlying database). The object I receive from that function is truly a Pydantic "Device" object. This has been my findings since I asked the question. :-) |
Beta Was this translation helpful? Give feedback.
Hi Mause,
Thank you for your reply.
This is caused by the underlying postgres library being used. I'm guessing there is some magic going on in the Record object of asyncpg. My guess is that the returned Record from the library does not expose the properties. Thus it requires to manually select the attributes to be fed into the pydantic model.
The function I provided above does the casting automatically when aiomysql is used (MySQL is the underlying database). The object I receive from that function is truly a Pydantic "Device" object.
This has been my findings since I asked the question. :-)