Created
January 24, 2013 18:07
-
-
Save zzzeek/4625858 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## NOTE: "inspect", "ashint", and calling select([SomeClass]) are | |
## all SQLAlchemy 0.8 features. To do this in 0.7 would require more | |
## internally-dependent code. | |
from sqlalchemy import * | |
from sqlalchemy.orm import * | |
from sqlalchemy.ext.declarative import declarative_base | |
from sqlalchemy.ext.compiler import compiles | |
from sqlalchemy.ext.hybrid import hybrid_property | |
from sqlalchemy.sql.expression import ColumnElement | |
from sqlalchemy import inspect | |
Base = declarative_base() | |
class NamePathColumn (ColumnElement): | |
def __init__(self, entity): | |
insp = inspect(entity) | |
self.entity = insp.selectable | |
@compiles(NamePathColumn) | |
def compile_name_path_column(element, compiler, **kwargs): | |
return "%s.node_path" % compiler.process(element.entity, ashint=True) | |
class Node(Base): | |
__tablename__ = 'node' | |
id = Column(Integer, primary_key=True) | |
@hybrid_property | |
def name_path(self): | |
raise NotImplementedError("we're just demoing @expression here...") | |
@name_path.expression | |
def name_path(cls): | |
return NamePathColumn(cls) | |
print select([Node]).where(Node.name_path == 'foobar') | |
na = aliased(Node) | |
print select([na]).where(na.name_path == 'foobar') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is excellent, I was wondering how I could solve the
aliased (Node)
part. (Typo correction:%s.name_path
instead of%s.node_path
). Now, I just how to understand it, lol. ;D Thanks!