Kludex / fastapi-microservices

Fully Python async FastAPI project! 🚀
MIT License
441 stars 43 forks source link

jsonable_encoder() is not working with many to many #68

Closed Bastien-BO closed 3 years ago

Bastien-BO commented 3 years ago

With a many to many complexe list relation jsonnable_encoder() will not work with session.add() the data part of the obj from jsonnable_encoder(obj_in) will have the same structure as dict(obj_in) but when you pass it at session.add(obj_in) it will raise a model mapping error wich is a deep rabbit hole since it is not the problem at all

It will not affect the beaviour of this project but in futur modification or if someone use it like me for a diferent use case it will

to recreate the behaviour you can use this sample of sqlamchemy models and relations:

class Permission(Base):
    __tablename__ = 'permission'
    id = Column(Integer, autoincrement=True, primary_key=True)
    name = Column(String(100), nullable=False, unique=True)

    roles = relationship("Role", secondary=role_permission, backref=backref('permissions', lazy=True), lazy='subquery')
class Role(Base):
    __tablename__ = 'role'
    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String(100), nullable=False, unique=True)
role_permission = Table('role_permission', Base.metadata,
                        Column('permission_id', ForeignKey('permission.id'), primary_key=True),
                        Column('role_id', ForeignKey('role.id'), primary_key=True)
                        )
Kludex commented 3 years ago

Yeah, I had this issue in the past.

Perfect! Thanks! 👍