7

Is there an equivalent of AR's named scopes? Named scopes are basically filters, that can be wrapped in a method, and then chained.

Here's an example from http://archives.ryandaigle.com/articles/2008/8/20/named-scope-it-s-not-just-for-conditions-ya-know:

class Article < ActiveRecord::Base

  # Get all articles that have been published
  named_scope :published, :conditions => ['published = ?', true]

  # Get all articles that were created recently
  named_scope :recent, lambda { { :conditions => ['created_at >= ?', 1.week.ago] } }

end

# Get all recently created articles that have been published
Article.published.recent

Here's an example using Django ORM: http://furrybrains.com/2009/06/22/named-scopes-for-django/

Vlad Zloteanu
  • 8,464
  • 3
  • 41
  • 58

1 Answers1

22

SQLAlchemy has hybrid attributes, which you could use to build any sort of system:

from sqlalchemy.ext.hybrid import hybrid_property


class Article(Base):
    @hybrid_property
    def published(self):
        return self.is_published == True

    @hybrid_property
    def recent(self):
        # this relies on the date arithmetic of the target backend
        return datetime.now() - self.created_at >= datetime.timedelta(days=7)


articles = query(Article).filter(Article.published, Article.recent).all()
Nikolay Shebanov
  • 1,363
  • 19
  • 33
zzzeek
  • 72,307
  • 23
  • 193
  • 185
  • This doesn't seem right. It appears to be doing an in memory comparison, rather than altering the SQL itself for an optimized query – Peter Ehrlich Oct 05 '15 at 21:56
  • 4
    @PeterEhrlich that's what it *seems* like, but if the object from which you call the methods is the Article class, not an Article object, these operations only produce SQL expressions. read [hybrid attributes](http://docs.sqlalchemy.org/en/latest/orm/extensions/hybrid.html) for more detail. – zzzeek Oct 15 '15 at 12:59