Active Record, Django-like queries, nested eager load and beauty __repr__ for SQLAlchemy
Active Record, Django-like queries, nested eager load and beauty __repr__ for SQLAlchemy
Note: As of v1.3, only python 3.5+ is supported.
A pack of framework-agnostic, easy-to-integrate and well tested mixins for SQLAlchemy ORM.
Heavily inspired by Django ORM and Eloquent ORM
Why it's cool:
from sqlalchemy_mixins import AllFeaturesMixin
class User(Base, AllFeaturesMixin):
passRussian readers, see related article on habrahabr.ru
Use pip
pip install sqlalchemy_mixinsRun tests
python -m unittest discover sqlalchemy_mixins/Here's a quick demo of what our mixins can do.
…See full example
To interactively play with this example from CLI, install iPython and type
ipython -i examples\all_features.py
…This library relies on SQLAlchemy's autocommit flag. It needs to be set to True when initializing the session i.e:
session = scoped_session(sessionmaker(bind=engine, autocommit=True))
BaseModel.set_session(session)or with Flask-SQLAlchemy
db = SQLAlchemy(app, session_options={'autocommit': True})Main features are
provided by ActiveRecordMixin
SQLAlchemy's Data Mapper pattern is cool, but Active Record pattern is easiest and more DRY.
Well, we implemented it on top of Data Mapper! All we need is to just inject session into ORM class while bootstrapping our app:
BaseModel.set_session(session)
# now we have access to BaseOrmModel.session propertyWe all love SQLAlchemy, but doing CRUD is a bit tricky there.
For example, creating an object needs 3 lines of code:
bob = User(name='Bobby', age=1)
session.add(bob)
session.flush()Well, having access to session from model, we can just write
bob = User.create(name='Bobby', age=1)that's how it's done in Django ORM and Peewee
update and delete methods are provided as well
bob.update(name='Bob', age=21)
bob.delete()And, as in Django and Eloquent, we can quickly retrieve object by id
User.find(1) # instead of session.query(User).get(1)and fail if such id doesn't exist
User.find_or_fail(123987) # will raise sqlalchemy_mixins.ModelNotFoundErrorSee full example and tests
As in Flask-SQLAlchemy, Peewee and Django ORM, you can quickly query some class
User.query # instead of session.query(User)Also we can quickly retrieve first or all objects:
User.first() # instead of session.query(User).first()
User.all() # instead of session.query(User).all()See full example and tests
provided by EagerLoadMixin
If you use SQLAlchemy's eager loading, you may find it not very convenient, especially when we want, say, load user, all his posts and comments to every his post in the same query.
Well, now you can easily set what ORM relations you want to eager load
User.with_({
User.posts: {
Post.comments: {
Comment.user: JOINED
}
}
}).all()Sometimes we want to load relations in separate query, i.e. do subqueryload. For example, we load posts on page like this, and for each post we want to have user and all comments (and comment authors).
To speed up query, we load comments in separate query, but, in this separate query, join user
from sqlalchemy_mixins import JOINED, SUBQUERY
Post.with_({
Post.user: JOINED, # joinedload user
Post.comments: (SUBQUERY, { # load comments in separate query
Comment.user: JOINED # but, in this separate query, join user
})
}).all()Here, posts will be loaded on first query, and comments with users - in second one. See SQLAlchemy docs for explaining relationship loading techniques.
For simple cases, when you want to just joinedload or subqueryload a few relations, we have easier syntax for you:
Comment.with_joined(Comment.user, Comment.post).first()
User.with_subquery(User.posts).all()See full example and tests
provided by SmartQueryMixin
We implement Django-like field lookups and automatic relation joins.
It means you can filter and sort dynamically by attributes defined in strings!
So, having defined Post model with Post.user relationship to User model,
you can write
Post.where(rating__gt=2, user___name__like='%Bi%').all() # post rating > 2 and post user name like ...
Post.sort('-rating', 'user___name').all() # sort by rating DESC, user name ASC(___ splits relation and attribute, __ splits attribute and operator)
If you need more flexibility, you can use low-level
filter_exprmethodsession.query(Post).filter(*Post.filter_expr(rating__gt=2, body='text')), see example.It's like
filter_byin SQLALchemy, but also allows magic operators likerating__gt.Note:
filter_exprmethod is very low-level and does NOT do magic Django-like joins. Usesmart_queryfor that.
All relations used in filtering/sorting should be explicitly set, not just being a backref
In our example,
Post.userrelationship should be defined inPostclass even ifUser.postsis defined too.So, you can't type
class User(BaseModel): # ... user = sa.orm.relationship('User', backref='posts')and skip defining
Post.userrelationship. You must define it anyway:class Post(BaseModel): # ... user = sa.orm.relationship('User') # define it anyway
For DRY-ifying your code and incapsulating business logic, you can use SQLAlchemy's hybrid attributes and hybrid_methods. Using them in our filtering/sorting is straightforward (see examples and tests).
See full example and tests
Well, as SmartQueryMixin does auto-joins for filtering/sorting,
there's a sense to tell sqlalchemy that we already joined that relation.
So that relations are automatically set to be joinedload if they were used for filtering/sorting.
So, if we write
comments = Comment.where(post___public=True, post___user___name__like='Bi%').all()then no additional query will be executed if we will access used relations
comments[0].post
comments[0].post.userCool, isn't it? =)
See full example and tests
provided by SmartQueryMixin
In real world, we want to filter, sort and also eager load some relations at once.
Well, if we use the same, say, User.posts relation in filtering and sorting,
it should not be joined twice.
That's why we combined filter, sort and eager load in one smartest method:
Comment.smart_query(
filters={
'post___public': True,
'user__isnull': False
},
sort_attrs=['user___name', '-created_at'],
schema={
Comment.post: {
Post.user: JOINED
}
}).all()** New in 0.2.3 ** In real world, you may need to "smartly" apply filters/sort/eagerload to any arbitrary query. And you can do this with standalone
smart_queryfunction:smart_query(any_query, filters=...)It's especially useful for filtering/sorting/eagerloading relations with lazy='dynamic' for pages like this:
smart_query(user.comments_, filters=...)See this example
** Experimental ** Additional logic (OR, AND, NOT etc) can be expressed using a nested structure for filters, with sqlalchemy operators (or any callable) as keys:
from sqlalchemy im
No open issues yet, or sync has not completed.