Escape the string paremeter used in SQL LIKE expressions.
from sqlalchemy_utils import escape_like
query = session.query(User).filter(
User.name.ilike(escape_like('John'))
)
Parameters: |
|
---|
Return the bind for given SQLAlchemy Engine / Connection / declarative model object.
Parameters: | obj – SQLAlchemy Engine / Connection / declarative model object |
---|
from sqlalchemy_utils import get_bind
get_bind(session) # Connection object
get_bind(user)
Return declarative class associated with given table. If no class is found this function returns None. If multiple classes were found (polymorphic cases) additional data parameter can be given to hint which class to return.
class User(Base):
__tablename__ = 'entity'
id = sa.Column(sa.Integer, primary_key=True)
name = sa.Column(sa.String)
get_class_by_table(Base, User.__table__) # User class
This function also supports models using single table inheritance. Additional data paratemer should be provided in these case.
class Entity(Base):
__tablename__ = 'entity'
id = sa.Column(sa.Integer, primary_key=True)
name = sa.Column(sa.String)
type = sa.Column(sa.String)
__mapper_args__ = {
'polymorphic_on': type,
'polymorphic_identity': 'entity'
}
class User(Entity):
__mapper_args__ = {
'polymorphic_identity': 'user'
}
# Entity class
get_class_by_table(Base, Entity.__table__, {'type': 'entity'})
# User class
get_class_by_table(Base, Entity.__table__, {'type': 'user'})
Parameters: |
|
---|---|
Returns: | Declarative class or None. |
Return the key for given column in given model.
Parameters: | model – SQLAlchemy declarative model object |
---|
class User(Base):
__tablename__ = 'user'
id = sa.Column(sa.Integer, primary_key=True)
name = sa.Column('_name', sa.String)
get_column_key(User, User.__table__.c._name) # 'name'
Return a collection of all Column objects for given SQLAlchemy object.
The type of the collection depends on the type of the object to return the columns from.
get_columns(User)
get_columns(User())
get_columns(User.__table__)
get_columns(User.__mapper__)
get_columns(sa.orm.aliased(User))
get_columns(sa.orm.alised(User.__table__))
Parameters: | mixed – SA Table object, SA Mapper, SA declarative class, SA declarative class instance or an alias of any of these objects |
---|
Returns the declarative base for given model class.
Parameters: | model – SQLAlchemy declarative model |
---|
Returns a dictionary of hybrid property keys and hybrid properties for given SQLAlchemy declarative model / mapper.
Consider the following model
from sqlalchemy.ext.hybrid import hybrid_property
class Category(Base):
__tablename__ = 'category'
id = sa.Column(sa.Integer, primary_key=True)
name = sa.Column(sa.Unicode(255))
@hybrid_property
def lowercase_name(self):
return self.name.lower()
@lowercase_name.expression
def lowercase_name(cls):
return sa.func.lower(cls.name)
You can now easily get a list of all hybrid property names
from sqlalchemy_utils import get_hybrid_properties
get_hybrid_properties(Category).keys() # ['lowercase_name']
Parameters: | model – SQLAlchemy declarative model or mapper |
---|
Return related SQLAlchemy Mapper for given SQLAlchemy object.
Parameters: | mixed – SQLAlchemy Table / Alias / Mapper / declarative model object |
---|
from sqlalchemy_utils import get_mapper
get_mapper(User)
get_mapper(User())
get_mapper(User.__table__)
get_mapper(User.__mapper__)
get_mapper(sa.orm.aliased(User))
get_mapper(sa.orm.aliased(User.__table__))
Return a list of all entities present in given SQLAlchemy query object.
Examples:
from sqlalchemy_utils import get_query_entities
query = session.query(Category)
get_query_entities(query) # [<Category>]
query = session.query(Category.id)
get_query_entities(query) # [<Category>]
This function also supports queries with joins.
query = session.query(Category).join(Article)
get_query_entities(query) # [<Category>, <Article>]
Parameters: | query – SQLAlchemy Query object |
---|
Return an OrderedDict of all primary keys for given Table object, declarative class or declarative class instance.
Parameters: | mixed – SA Table object, SA declarative class or SA declarative class instance |
---|
get_primary_keys(User)
get_primary_keys(User())
get_primary_keys(User.__table__)
get_primary_keys(User.__mapper__)
get_primary_keys(sa.orm.aliased(User))
get_primary_keys(sa.orm.aliased(User.__table__))
See also
Return a set of tables associated with given SQLAlchemy object.
Let’s say we have three classes which use joined table inheritance TextItem, Article and BlogPost. Article and BlogPost inherit TextItem.
get_tables(Article) # set([Table('article', ...), Table('text_item')])
get_tables(Article())
get_tables(Article.__mapper__)
If the TextItem entity is using with_polymorphic=’*’ then this function returns all child tables (article and blog_post) as well.
get_tables(TextItem) # set([Table('text_item', ...)], ...])
Parameters: | mixed – SQLAlchemy Mapper, Declarative class, Column, InstrumentedAttribute or a SA Alias object wrapping any of these objects. |
---|
Simple shortcut function for checking if given attributes of given declarative model object have changed during the session. Without parameters this checks if given object has any modificiations. Additionally exclude parameter can be given to check if given object has any changes in any attributes other than the ones given in exclude.
from sqlalchemy_utils import has_changes
user = User()
has_changes(user, 'name') # False
user.name = u'someone'
has_changes(user, 'name') # True
has_changes(user) # True
You can check multiple attributes as well.
has_changes(user, ['age']) # True
has_changes(user, ['name', 'age']) # True
This function also supports excluding certain attributes.
has_changes(user, exclude=['name']) # False
has_changes(user, exclude=['age']) # True
Parameters: |
|
---|
Return the identity of given sqlalchemy declarative model class or instance as a tuple. This differs from obj._sa_instance_state.identity in a way that it always returns the identity even if object is still in transient state ( new object that is not yet persisted into database). Also for classes it returns the identity attributes.
from sqlalchemy import inspect
from sqlalchemy_utils import identity
user = User(name=u'John Matrix')
session.add(user)
identity(user) # None
inspect(user).identity # None
session.flush() # User now has id but is still in transient state
identity(user) # (1,)
inspect(user).identity # None
session.commit()
identity(user) # (1,)
inspect(user).identity # (1, )
You can also use identity for classes:
identity(User) # (User.id, )
Parameters: | obj – SQLAlchemy declarative model object |
---|
Return whether or not given property of given object has been loaded.
class Article(Base):
__tablename__ = 'article'
id = sa.Column(sa.Integer, primary_key=True)
name = sa.Column(sa.String)
content = sa.orm.deferred(sa.Column(sa.String))
article = session.query(Article).get(5)
# name gets loaded since its not a deferred property
assert is_loaded(article, 'name')
# content has not yet been loaded since its a deferred property
assert not is_loaded(article, 'content')
Parameters: |
|
---|
Make query order by deterministic (if it isn’t already). Order by is considered deterministic if it contains column that is unique index ( either it is a primary key or has a unique index). Many times it is design flaw to order by queries in nondeterministic manner.
Consider a User model with three fields: id (primary key), favorite color and email (unique).:
from sqlalchemy_utils import make_order_by_deterministic
query = session.query(User).order_by(User.favorite_color)
query = make_order_by_deterministic(query)
print query # 'SELECT ... ORDER BY "user".favorite_color, "user".id'
query = session.query(User).order_by(User.email)
query = make_order_by_deterministic(query)
print query # 'SELECT ... ORDER BY "user".email'
query = session.query(User).order_by(User.id)
query = make_order_by_deterministic(query)
print query # 'SELECT ... ORDER BY "user".id'
Returns whether or not two given SQLAlchemy declarative instances are naturally equivalent (all their non primary key properties are equivalent).
from sqlalchemy_utils import naturally_equivalent
user = User(name=u'someone')
user2 = User(name=u'someone')
user == user2 # False
naturally_equivalent(user, user2) # True
Parameters: |
|
---|
Conditionally quote an identifier.
from sqlalchemy_utils import quote
engine = create_engine('sqlite:///:memory:')
quote(engine, 'order')
# '"order"'
quote(engine, 'some_other_identifier')
# 'some_other_identifier'
Parameters: |
|
---|
Applies an sql ORDER BY for given query. This function can be easily used with user-defined sorting.
The examples use the following model definition:
import sqlalchemy as sa
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy_utils import sort_query
engine = create_engine(
'sqlite:///'
)
Base = declarative_base()
Session = sessionmaker(bind=engine)
session = Session()
class Category(Base):
__tablename__ = 'category'
id = sa.Column(sa.Integer, primary_key=True)
name = sa.Column(sa.Unicode(255))
class Article(Base):
__tablename__ = 'article'
id = sa.Column(sa.Integer, primary_key=True)
name = sa.Column(sa.Unicode(255))
category_id = sa.Column(sa.Integer, sa.ForeignKey(Category.id))
category = sa.orm.relationship(
Category, primaryjoin=category_id == Category.id
)
1. Applying simple ascending sort
query = session.query(Article)
query = sort_query(query, 'name')
2. Appying descending sort
query = sort_query(query, '-name')
3. Applying sort to custom calculated label
query = session.query(
Category, sa.func.count(Article.id).label('articles')
)
query = sort_query(query, 'articles')
4. Applying sort to joined table column
query = session.query(Article).join(Article.category)
query = sort_query(query, 'category-name')
Parameters: |
|
---|