Skip to content

Instantly share code, notes, and snippets.

@zzzeek
Created January 24, 2013 18:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zzzeek/4625858 to your computer and use it in GitHub Desktop.
Save zzzeek/4625858 to your computer and use it in GitHub Desktop.
## 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')
@hsk81
Copy link

hsk81 commented Jan 24, 2013

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment