35π
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()
π€Connor
5π
Probably, you are looking for ORM events.
Take a look at instance events and session events.
π€Ernest
- [Django]-Automatic creation date for Django model form objects
- [Django]-Can I manually trigger signals in Django?
- [Django]-Django check for any exists for a query
4π
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.
- [Django]-What's the difference between ContentType and MimeType?
- [Django]-Django nested transactions β βwith transaction.atomic()β
- [Django]-Django REST framework serializer without a model
- [Django]-Django DB Settings 'Improperly Configured' Error
- [Django]-Django package to generate random alphanumeric string
- [Django]-Django template: check for empty query set
Source:stackexchange.com