[英]Is there an equivalent of ActiveRecord's find(:include) in Elixir/SQLAlchemy?
[英]SQLAlchemy equivalent of named scopes in ActiveRecord
是否有相当于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/
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.