7

AR の名前付きスコープに相当するものはありますか? 名前付きスコープは基本的にフィルターであり、メソッドでラップしてチェーンすることができます。

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

Django ORM を使用した例を次に示します: http://furrybrains.com/2009/06/22/named-scopes-for-django/

4

1 に答える 1

19

SQLAlchemy にはハイブリッド属性があり、あらゆる種類のシステムを構築するために使用できます。

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()
于 2013-01-31T00:12:42.973 に答える