You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
When trying to fix the issue, I realized that pydantic tries serializing the document returned but fails due to the __dict__ method not returning serialized data properly. I also tried working with `.to_mongo()', but pydantic failed to serialize the ObjectID fields.
I read some posts on stack overflow and the suggested solution was to return .to_json() which can be returned as a JSON string, but due to the number of routes making use of this, it would be a hassle to update every single route to return .to_json, also the frontend dev would have to then parse all responses from the API back to JSON which is unnecessary
I ended up having to create an abstract document with a fix to the __dict__ method:
classCustomDocument(Document):
meta= {"abstract": True}
@propertydef__dict__(self):
data= {} # initialize an empty dictionary to store the converted data# iterate over key-value pairs in the to_mongo() resultforkey, valueinself.to_mongo().items():
# check if the value is an ObjectId and convert it to a string if necessaryvalue=str(value) ifisinstance(value, ObjectId) elsevalue# update the dictionary with the key-value pairdata.update({key: value})
returndataclassModelName(CustomDocument):
name=StringField(required=True)
title=StringField(required=True)
I'd love to know if there is already a solution for this, or possibly one already being worked on. If there isn't, I'll create a pull request with a possible fix to make things easier.
Thank you.
The text was updated successfully, but these errors were encountered:
I am trying to integrate Mongoengine ORM with Fastapi but am experiencing an issue when trying to return routes:
demo model:
route integration:
what is returned:
When trying to fix the issue, I realized that pydantic tries serializing the document returned but fails due to the
__dict__
method not returning serialized data properly. I also tried working with `.to_mongo()', but pydantic failed to serialize the ObjectID fields.I read some posts on stack overflow and the suggested solution was to return
.to_json()
which can be returned as a JSON string, but due to the number of routes making use of this, it would be a hassle to update every single route to return.to_json
, also the frontend dev would have to then parse all responses from the API back to JSON which is unnecessaryI ended up having to create an abstract document with a fix to the
__dict__
method:returned:
I'd love to know if there is already a solution for this, or possibly one already being worked on. If there isn't, I'll create a pull request with a possible fix to make things easier.
Thank you.
The text was updated successfully, but these errors were encountered: