On Aug 8, 2013, at 7:47 PM, askel <dummy...@mail.ru> wrote: > Hello everyone, > > I've been using SQLAlchemy for a while and it's been a pleasure. But > sometimes I feel I can get a little more from it or do something more > properly. For instance, imagine two tables with one-to-one relationship bosth > sharing the same primary key and second table containing primary key only > (please don't ask me why it wasn't made just a nullable boolean column to the > first table). > > Base = declarative_base() > > class Item(Base): > __table_name__ = 'items' > > i_id = Column(Integer, primary_key=True) > # other columns omitted > > special_items = Table('special_items', Base.metadata, > Column('i_id', Integer, ForeignKey('items.i_id'), primary_key=True), > # no any other columns > ) > > Item.is_special = exists([1]).where(Item.i_id == special_items.c.i_id) > > And sometimes I need to use that is_special property in query filter as the > following: > > query(Item).filter(and_(Item.is_special, ...)) > > which works well in queries -- exists sub-query is added if/whenever > is_special is mentioned in filter. > > What I would also like to see is is_special becoming a boolean property of > Items instance. And it would be awesome to be able to assign to it so that it > fires correct insert statement when session is flushed. > > To make first thing happen it sounds like I need to use hybrid_property but I > couldn't figure out what is_special method should return when it's accessed > as instance property. More over that property should be lazy, i. e. I don't > want every query have that exists sub-query UNLESS it's explicitly used in > filter or any other way. > > class Item(Base): > ... > @hybrid_property > def is_special(self): > return ??? > > @is_special.statement > def is_special(cls): > return exists([1]).where(cls.i_id == special_items.c.i_id) > > > I'd greatly appreciate if anybody gives me tip on how to make above happen > (may be partially). It's not like I cannot live without it though.
seems like you'd create Item.special_items as a relationship() to the special_items table (using some class), then the python is_special() just says return bool(self.special_items). If you create the relationship() with lazy=dynamic you could just say bool(self.special_items.count()).
signature.asc
Description: Message signed with OpenPGP using GPGMail