I had the same problem and decided to look into implementing a custom relationship like you suggested. I'll post what I have here in case anyone else has the same problem. :)
The first thing I noticed was the query_class attribute on the RelationshipProperty class. If you don't want to implement a new relationship, you can just do this, which is a little cleaner than respecifying the primaryjoin: children = relationship(Child, query_class=MyPrefilteredQuery) (Where MyPrefilteredQuery is the PreFilteredQuery class you implemented as per https://bitbucket.org/zzzeek/sqlalchemy/wiki/UsageRecipes/PreFilteredQuery .) Making your own relationship is pretty straightforward from there, though: from sqlalchemy.util.langhelpers import public_factory from sqlalchemy.orm.relationships import RelationshipProperty class MyPrefilteredRelationship(RelationshipProperty): def __init__(self, *args, **kwargs): kwargs['query_class'] = MyPrefilteredQuery super(MyPrefilteredRelationship, self).__init__(*args, **kwargs) filtered_relationship = public_factory(MyPrefilteredRelationship, ".mylib.db") Then you can use it like so: from mylib.db import filtered_relationship class Parent(Base): __table__ = parent_table children = filtered_relationship(Child) On Sunday, February 20, 2011 8:19:58 PM UTC-8, robert wrote: > > On Feb 20, 8:59 pm, Michael Bayer <[email protected]> wrote: > > the cleanest and most foolproof way is to join on relationships that > have the condition: > > > > related_non_deleted = relationship(Related, > primaryjoin=and_(Related.deleted==False, Related.foo_id==id), > viewonly=True) > > I agree that the explicit approach is the most foolproof. The main > reason I was trying to avoid it is that, in my case, the condition is > ubiquitous. Thus all of my relationships that look like this > > children = relationship(Child) > > would have to change to > > children = relationship(Child, primaryjoin=and_(Child.deleted==False, > Child.parent_id==id) > > Perhaps I could write a custom relationship() to simplify things. > I'll give that a try. I'll also have to > add .filter(foo.deleted==False) to all top level queries. Maybe a > custom Session that always answers a query with that filter already > added would be cleaner. There may ultimately be many queries and many > relationships in this app, and I'm trying to avoid having to remember > (or worse, have someone else remember) to always include the deleted > condition. > > Thanks for your help. I've got a bit of digging to do now. -- 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 [email protected]. To post to this group, send email to [email protected]. Visit this group at http://groups.google.com/group/sqlalchemy. For more options, visit https://groups.google.com/d/optout.
