SQLAlchemy Model Django like Save Method?

耗尽温柔 提交于 2019-12-31 10:58:12

问题


I am using sqlalchemy for a project. However, I am more accustomed to Django's ORM.

I would like to know if, in the sqlachemy ORM, there is anything similar to a Django models' save() method that I can overrride to implement actions automatically upon a 'commit' / 'save.'


回答1:


You can extend your models with some simple crud methods to achieve something similar to Django ORM / ActiveRecord:

# SQLAlchemy db_session setup omitted
...

Model = declarative_base(name='Model')
Model.query = db_session.query_property()

class CRUD():

     def save(self):
         if self.id == None:
             db_session.add(self)
         return db_session.commit()

      def destroy(self):
          db_session.delete(self)
          return db_session.commit()

class User(Model, CRUD):
    __tablename__ = 'users'
    id = db.Column(db.integer, primary_key=True)
    email = db.Column(db.String(120), unique=True)

    def __init__(self, email):
        self.email = email

You can then save or destroy the model as needed:

user = User('example@example.com')
user.save()



回答2:


Probably, you are looking for ORM events.

Take a look at instance events and session events.




回答3:


Good news for you!

I created package for that. It implements Active Record pattern for SQLAlchemy.

See https://github.com/absent1706/sqlalchemy-mixins#active-record

It also has many very useful features such as Django lookups that span relationship, declarative eager load and readable print for SQAlchemy.



来源:https://stackoverflow.com/questions/31584974/sqlalchemy-model-django-like-save-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!