SQLAlchemy 1.1关系自动过滤

时间:2016-02-25 19:47:30

标签: python sqlalchemy

我基本上和one from 7 years ago有同样的问题,但我想知道SQLAlchemy的最新版本中是否有任何改变。

我有一组ORM模型都带有一个启用的布尔值,以及它们之间的许多关系。我的惯例是,如果记录未启用,则不应在结果中显示。然而,这似乎意味着我必须在关系上手动指定完整的主连接。我想知道是否有更自动的方法来实现我的结果。

我目前的设置:

import sqlalchemy as sa
import sqlalchemy.orm as saorm
from sqlalchemy.ext.declarative import as_declarative

@as_declarative()  # pylint: disable=too-few-public-methods
class Base(object):
    """ Declarative base for ORM. """
    pass

class BaseModel(Base):
    """ Base for all Models. Should not be instantiated directly, but rather
    subclassed for actual models. """
    __abstract__ = True
    id = sa.Column(sa.Integer, primary_key=True)  # pylint: disable=invalid-name
    enabled = sa.Column(sa.Boolean, default=True, server_default=sa.text('true'), nullable=False)

class Accounts(BaseModel):
    """ A collection of Users """
    __tablename__ = 'accounts'
    name = sa.Column(sa.String(100), nullable=False)

    users = saorm.relationship('Users', back_populates='account')

class Users(BaseModel):
    """ Users have unique emails and are associated with Accounts. """
    __tablename__ = 'users'
    account_id = sa.Column(sa.Integer, sa.ForeignKey('accounts.id'))
    email = sa.Column(sa.String(100), unique=True, nullable=False)

    account = saorm.relationship('Accounts', back_populates='users')

使用此功能,我可能会要求提供帐户中所有用户的列表:

from settings import CONNECTION_URL
engine = sa.create_engine(CONNECTION_URL)
Session = saorm.sessionmaker(bind=engine)
session = Session()
acnt = session.query(Account).filter(Account.id == 1).one()
print(acnt.users)

[<Users(id=82, enabled=False, account_id=1, email='WZV7a7GQTs@VIiwi.nc2')>,
 <Users(id=83, enabled=False, account_id=1, email='HblDwX1As2@FkRPZ.Ju4')>,
 <Users(id=84, enabled=True, account_id=1, email='VMspJkHPgA@LJS5W.DXl')>,
 <Users(id=85, enabled=True, account_id=1, email='YPHFF8gkNp@1rnOr.mRM')>]

但这包括被禁用的用户82和83。因此,我必须在与帐户的用户关系中添加一个主连接:

users = saorm.relationship('Users', back_populates='account',
                           primaryjoin="and_(Accounts.id==Users.account_id, Users.enabled)")

我是否可以通过某种方式建立默认为检查远程启用标志的关系?

0 个答案:

没有答案