【问题标题】:SQLAlchemy equivalent of named scopes in ActiveRecordSQLAlchemy 等效于 ActiveRecord 中的命名范围
【发布时间】:2013-01-30 08:53:09
【问题描述】:

是否存在与 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/

【问题讨论】:

    标签: python orm sqlalchemy named-scope


    【解决方案1】:

    SQLAlchemy 有 hybrid attributes,您可以使用它来构建任何类型的系统:

    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()
    

    【讨论】:

    • 这似乎不对。它似乎是在进行内存比较,而不是为了优化查询而改变 SQL 本身
    • @PeterEhrlich 这就是它看起来的样子,但是如果您从中调用方法的对象是 Article 类,而不是 Article 对象,那么这些操作只会产生 SQL 表达式。阅读hybrid attributes了解更多详情。
    猜你喜欢
    • 1970-01-01
    • 2012-03-16
    • 2022-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-14
    • 1970-01-01
    相关资源
    最近更新 更多