Yoann Roman wrote:
> Given the following relationships:
>
> employees_table = Table('employees', metadata,
>     Column('id', Integer, primary_key=True),
>     Column('row_type', Integer, nullable=False)
>     Column('name', String(50)),
>     Column('is_certified', Boolean)
> )
>
> employee_mapper = mapper(Employee, employees_table,
>     polymorphic_on=employees_table.c.row_type,
> polymorphic_identity=1,
>     exclude_properties=['is_certified'])
> manager_mapper = mapper(Manager, inherits=employee_mapper,
> polymorphic_identity=2,
>     properties={
>         'is_certified': employees_table.c.is_certified
>     })
>
> How can I query for employees who aren't managers or managers who are
> certified without referring to the polymorphic identity? Basically,
> without doing this:
>
> session.query(Employee).filter(or_(Employee.row_type!=2,
> Manager.is_certified==True))

the ultimate SQL must include the "row_type" column, or perhaps you could
detect if "is_certified" is NULL to detect a non-manager row.   There's no
way to get around having to tell your query "check the type of the object"
somehow.

However, if you're just disturbed about the actual "row_type" column and
the hardcoding of "2", you can make yourself an operator pretty easily
here.   A simple one is like:

def isinstance_(cls_):
    mapper = class_mapper(cls_)
    return mapper.polymorphic_on == mapper.polymorphic_identity

a more comprehensive one that takes into account further subclasses:

def isinstance_(cls_):
    mapper = class_mapper(cls_)
    return mapper.polymorphic_on.in_(
                    [m.polymorphic_identity
                    for m in mapper.polymorphic_iterator()]
                )

a query like:

sess.query(Employee).filter(~isinstance_(Manager))

would render:

SELECT *
FROM employees
WHERE employees.row_type NOT IN (...)




>
> Thanks!
>
> --
> You received this message because you are subscribed to the Google Groups
> "sqlalchemy" group.
> To post to this group, send email to sqlalch...@googlegroups.com.
> To unsubscribe from this group, send email to
> sqlalchemy+unsubscr...@googlegroups.com.
> For more options, visit this group at
> http://groups.google.com/group/sqlalchemy?hl=en.
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To post to this group, send email to sqlalch...@googlegroups.com.
To unsubscribe from this group, send email to 
sqlalchemy+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en.

Reply via email to