On Apr 16, 2013, at 9:30 AM, Richard Gerd Kuesters <rich...@humantech.com.br> wrote:
> Hello all! > > Ok, maybe people asks this a lot, but I wonder if it's possible to perform a > query using an object as a filter - and I searched for it, didn't found > anything close to my idea. > > Simple dumb example code: > > > class User(Base): > > user_id = Column(Integer, Sequence(...), primary_key=True) > username = Column(Unicode) > > > class Subscription(Base): > > subscription_id = Column(Integer, Sequence(...), primary_key=True) > name = Column(unicode) > owner_id = Column(Integer, ForeignKey('user.user_id'), nullable=False) > > @hybrid_property > def owner(self): > if not object_session(self): > return None > return object_session(self).query(User).filter(self.owner_id == > User.user_id).first() > > @owner.setter > def owner(self, owner): > self.owner_id = owner.user_id if isinstance(owner, User) else owner > if object_session(self): > object_session(self).commit() > > # @owner.expression # ??? > > > # ok, so far *almost* good OK, all of that complexity with hybrid_property is not needed at all here. Just say, "owner = relationship("User")", and you're done. SQLAlchemy manages one-to-many, many-to-one, and many-to-many automatically with relationship(). > > > # but, i would like to do _this_ instead > > print session.query(Subscription).filter(Subscription.owner == new_user).all() > > > I've tried it in so many ways that I feel dizzy. The only way I think would > be using @owner.expression to "return User", but that didn't the trick, it > only appends "WHERE false" to the query, hehehe. yeah just use relationship(), and you'd be using the first operator as described right here in the ORM tutorial (which is a must-read): http://docs.sqlalchemy.org/en/rel_0_8/orm/tutorial.html#common-relationship-operators -- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To post to this group, send email to sqlalchemy@googlegroups.com. Visit this group at http://groups.google.com/group/sqlalchemy?hl=en. For more options, visit https://groups.google.com/groups/opt_out.