Many to many bidirectional relationship is not JSON serializable #10
Comments
I also noticed this, I ended up adding all the relational items to json_hidden I would be interested in your answer as well. Nick |
I understand that the class ProjectJsonSerializer(JsonSerializer):
__json_modifiers__ = {
'users': lambda users, _: [dict(id=user.id) for user in users]
} This will render a JSON response like such: {
"id": 1,
"name": "project name",
"users": [
{
"id": 1
},
{
"id": 2
}
]
} Adjust the modifier to your liking to render the appropriate JSON object. |
Thanks Matt, that worked perfectly! I now have a better understanding of lambda after reading some tutorials and from your answer. |
Great answer by the way. Thanks for sharing. |
Hi Matt, firstly I appreciate you making this template an open source project. It has really helped me understand serializing alembic models into JSON format. I am trying to better understand your JSONSerializer class and the JSON modifier you provided in this issue. Can you tell me if I am understanding the logic for the
The following is my understanding of how the code is executing:
Am I understanding the execution correctly? |
When I try to access a model with a bidirectional many to many relationship, I get the error:
TypeError: <sqlalchemy.orm.dynamic.AppenderBaseQuery object at 0x2a01b50> is not JSON serializable
The error makes sense, asrv = {..., 'users': <sqlalchemy.orm.dynamic.AppenderBaseQuery object at 0x2758b50>}
.How would I go about executing that query so it becomes serialized?
__json_modifiers__
for 'users' and run a lambda to convert it to a list/json?sqlalchemy
that can resolve this?Thanks so much for your flask skeleton project. It has cleared up so many questions I had about how to scale large projects.
The text was updated successfully, but these errors were encountered: