Adding a filter_by() clause by default.

30 views
Skip to first unread message

RommeDeSerieux

unread,
Jun 23, 2008, 1:42:34 PM6/23/08
to sqlal...@googlegroups.com
In my application, a lot of models have a deleted_at field which is
either null or set to a date. And in most places where i select from
those models, i only need the instances where deleted_at is null. Of
course, i can do it manually by adding just another filter_at on every
ORM operation, but that's error-prone and breaks the DRY severely.

But i've read on the sqlalchemy website that it's quite extensible, so
how can i do it automatically for certain tables? I'm looking for
something like Django ORM's custom managers.

Michael Bayer

unread,
Jun 23, 2008, 3:27:50 PM6/23/08
to sqlalchemy
using 0.5:

from sqlalchemy.orm import Query, sessionmaker

class MyQuery(Query):
def __new__(cls, entities, **kwargs):
if hasattr(entities[0], 'deleted_at'):
return Query(entities,
**kwargs).filter_by(deleted_at=None)
else:
return object.__new__(cls)

Session = sessionmaker(query_cls=MyQuery)

Huy Do

unread,
Jun 25, 2008, 7:56:35 PM6/25/08
to sqlal...@googlegroups.com
This is cool stuff.

huy

Reply all
Reply to author
Forward
0 new messages