How to update sqlalchemy orm object by a python dict

前端 未结 4 1931
故里飘歌
故里飘歌 2020-12-01 06:24

the dict\'s key names are mapping to the sqlalchemy object attrs

ex:

class User(Base):
    __tablename__ = \'users\'

    id = Column(Integer, primar         


        
4条回答
  •  执笔经年
    2020-12-01 07:04

    I have another solution here. It would be handy to define model method as following.

    class ModelName(db.Model):
        """
        docstring here
        """
        ...
    
        def update(self, **kwargs):
            for key, value in kwargs.items():
                if hasattr(self, key):
                    setattr(self, key, value)
    

    I hope it would solve your problem.

    Thank you

提交回复
热议问题