Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy Model Django like Save Method?

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.'

like image 489
David Simic Avatar asked Jul 23 '15 10:07

David Simic


People also ask

Can I use SQLAlchemy with Django?

Both Django and SQLAlchemy can be used with MySQL, PostgreSQL, Oracle and SQLite. If you're using MSSQL, you should go for SQLAlchemy, as it's fully supported by it and you'll find more information and documentation about it.

Is SQLAlchemy ORM slow?

SQLAlchemy is very, very fast. It's just that users tend to be unaware of just how much functionality is being delivered, and confuse an ORM result set with that of a raw database cursor.

Should I use SQLAlchemy core or ORM?

If you want to view your data in a more schema-centric view (as used in SQL), use Core. If you have data for which business objects are not needed, use Core. If you view your data as business objects, use ORM. If you are building a quick prototype, use ORM.

Is it worth using SQLAlchemy?

SQLAlchemy is great because it provides a good connection / pooling infrastructure; a good Pythonic query building infrastructure; and then a good ORM infrastructure that is capable of complex queries and mappings (as well as some pretty stone-simple ones).


3 Answers

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('[email protected]')
user.save()
like image 53
Connor Avatar answered Oct 18 '22 01:10

Connor


Probably, you are looking for ORM events.

Take a look at instance events and session events.

like image 21
Ernest Ten Avatar answered Oct 18 '22 01:10

Ernest Ten


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.

like image 4
Alexander Litvinenko Avatar answered Oct 18 '22 00:10

Alexander Litvinenko