django_sorcery.db.query module

sqlalchemy query related things.

class django_sorcery.db.query.Operation(name, args, kwargs)

Bases: tuple


Alias for field number 1


Alias for field number 2


Alias for field number 0

class django_sorcery.db.query.Query(entities, session=None)[source]

Bases: sqlalchemy.orm.query.Query

A customized sqlalchemy query.

filter(*args, **kwargs)[source]

Standard SQLAlchemy filtering plus django-like expressions can be provided:

For example:

MyModel.objects.filter( == 5)
get(*args, **kwargs)[source]

Return an instance based on the given primary key identifier, either as args or kwargs for composite keys.

If no instance is found, returns None.


Standard SQLAlchemy ordering plus django-like expressions can be provided:

For example:

class django_sorcery.db.query.QueryProperty(db, model=None, *args, **kwargs)[source]

Bases: object

A property class that returns a session scoped query object against the class when called. Used by the SQLAlchemy.queryproperty

For example:

>>> class MyView(object):
...     queryset = db.queryproperty(FooModel)

You can even pass default filtering criteria if needed:

>>> class MyView(object):
...     queryset = db.queryproperty(FooModel, to_be_deleted=False)

In addition this pattern can be used to implement Django’s ORM style model managers:

>>> class UserModel(db.Model):
...     id = db.Column(db.Integer(), primary_key=True)
...     username = db.Column(db.String())
...     is_active = db.Column(db.Boolean())
...     active = db.queryproperty(is_active=True)

That can be used directly:

>>> UserModel.metadata.create_all(bind=db.engine)
>>> db.add_all([
...     UserModel(id=1, username='foo', is_active=False),
...     UserModel(id=2, username='bar', is_active=True),
... ])
>>> db.flush()

>>> UserModel.objects.all()
[UserModel(id=1, is_active=False, username='foo'), UserModel(id=2, is_active=True, username='bar')]
[UserModel(id=2, is_active=True, username='bar')]

This pattern is very useful when combined with Django style views:

>>> class MyView(object):
...     queryset =

>>> MyView().queryset.all()
[UserModel(id=2, is_active=True, username='bar')]

Additional filters/options can be applied as well:

>>> class MyView(object):
...     queryset = == 'test')

>>> MyView().queryset.all()