Yannick Gingras | 13 May 22:50

Query filtering like isinstance()

Greetings Alchemists, 
  some part of my application receives a partly filtered query and
applies additional criteria.  At one place, the query is on an object
hierarchy and I want to do a filter similar to isinstance().  Let's
look at this example:

------------------------------
items_table = Table('items', meta,
                    Column('id', Integer, primary_key=True),
                    Column('name', UnicodeText, nullable=False, 
                           unique=True),
                    Column('_type', Text, nullable=False))
class Item(object):
    def __repr__(self):
        return "<%s %s>" % (self.__class__.__name__, self.name)

mapper(Item, items_table, 
       polymorphic_on=items_table.c._type, 
       polymorphic_identity='item')

containers_table = Table('containers', meta,
                         Column('id', Integer, 
                                ForeignKey("items.id"),
                                primary_key=True))
class Container(Item):
    pass

mapper(Container, containers_table, 
       inherits=Item, polymorphic_identity='container')

areas_table = Table('areas', meta,
                    Column('id', Integer, 
                           ForeignKey("containers.id"),
                           primary_key=True))
class Area(Container):
    pass

mapper(Area, areas_table, 
       inherits=Container, polymorphic_identity='area')
------------------------------

If I want to query on containers and on area, I can simply do

  q = Container.query().filter(...)

but, if I receive a query on Item and a base class, say either Item,
Container or Area, how can I filter() my query to receive only the
sub-items from this base class?  

I'm looking for a method of filtering that would produce the same
result as:

  q = Item.query()
  # ... do some filtering
  filtered_cont_and_area = [i for i in q.all() if isinstance(i, Container)]

See the attached example for a more detailed example for what I'm
looking for.

--

-- 
Yannick Gingras

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

Attachment (alchemy-hier-test.py): text/x-python, 2044 bytes

Gmane