Let's say I have the following model with a synonym for the "code"
column that is called "value":


from elixir import *
from sqlalchemy import create_engine, and_

engine = create_engine('sqlite:///:memory:', echo=True)
metadata.bind = engine

class Node(Entity):
    using_options(tablename='nodes')

    parent = ManyToOne('Node')

    code = Field(String(20), unique=True)
    name = Field(String(50))
    lft = Field(Integer)
    rgt = Field(Integer)

    value = Synonym('code')

setup_all(True)

n2 = Node.table.alias('n2')

query = Node.query.filter(and_(n2.c.code == 'xxx',
                               n2.c.lft <= Node.c.lft,
                               n2.c.rgt >= Node.c.rgt))


The query above works fine. However, if I want the query to refer to
"value" instead of "code", I just couldn't find a clean way to do so.

Here's one workaround that retrieves the actual column name from the
synonym and then uses it in the query:


prop = Node.mapper.get_property('value')
if hasattr(prop, 'name'):
    colname = prop.name
else:
    colname = prop.key

query = Node.query.filter(and_(n2.c[colname] == 'xxx',
                               n2.c.lft <= Node.c.lft,
                               n2.c.rgt >= Node.c.rgt))


Another workaround is to modify table.c so that it is possible to use
table.c.value:


Group.c['value'] = Group.c.code

query = Node.query.filter(and_(n2.c.value == 'xxx',
                               n2.c.lft <= Node.c.lft,
                               n2.c.rgt >= Node.c.rgt))


What I prefer is to make it possible to alias the Entity, and then use
it directly in query and have it resolves the synonym transparently,
i.e.:


n2 = Node.alias('n2')

query = Node.query.filter(and_(n2.value == 'xxx',
                               n2.lft <= Node.lft,
                               n2.rgt >= Node.rgt))


Which way do you think is the cleanest? Is there any other workaround?

Regards,
Yap

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"SQLElixir" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/sqlelixir?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to