sqlalchemy按模型过滤,具有多个关系引用

时间:2017-11-29 08:28:04

标签: python sqlalchemy relation declarative

例如,我有Parcel模型,其senderreceiver都是Subject。 我试图从特定发件人那里获得包裹。我不想使用Parcel.sender.has(),因为性能,我真正的桌子太大了。

来自docs

  

因为has()使用了相关的子查询,所以与大型目标表相比,它的性能与使用连接时的表现差不多。

以下是完整的粘贴并运行示例:

from sqlalchemy import create_engine, Column, Integer, Text, ForeignKey
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy.ext.declarative.api import declarative_base
from sqlalchemy.orm.util import aliased

engine = create_engine('sqlite://')
Session = sessionmaker(bind=engine)
s = Session()

Base = declarative_base()


class Subject(Base):
    __tablename__ = 'subject'

    id = Column(Integer, primary_key=True)
    name = Column(Text)


class Parcel(Base):
    __tablename__ = 'parcel'

    id = Column(Integer, primary_key=True)
    sender_id = Column(Integer, ForeignKey('subject.id'))
    receiver_id = Column(Integer, ForeignKey('subject.id'))

    sender = relationship('Subject', foreign_keys=[sender_id], uselist=False, lazy='joined')
    receiver = relationship('Subject', foreign_keys=[receiver_id], uselist=False, lazy='joined')

    def __repr__(self):
        return '<Parcel #{id} {s} -> {r}>'.format(id=self.id, s=self.sender.name, r=self.receiver.name)


# filling database
Base.metadata.create_all(engine)
p = Parcel()
p.sender, p.receiver = Subject(name='Bob'), Subject(name='Alice')
s.add(p)
s.flush()


#
# Method #1 - using `has` method - working but slow
print(s.query(Parcel).filter(Parcel.sender.has(name='Bob')).all())

所以,我试图通过别名关系加入和过滤,这引发了一个错误:

#
# Method #2 - using aliased joining - doesn't work
# I'm getting next error: 
#
# sqlalchemy.exc.InvalidRequestError: Could not find a FROM clause to join from.  
# Tried joining to <AliasedClass at 0x7f24b7adef98; Subject>, but got: 
# Can't determine join between 'parcel' and '%(139795676758928 subject)s'; 
# tables have more than one foreign key constraint relationship between them. 
# Please specify the 'onclause' of this join explicitly.
#
sender = aliased(Parcel.sender)
print(s.query(Parcel).join(sender).filter(sender.name == 'Bob').all())

我发现如果我使用连接条件而不是关系来指定模型,它就会起作用。但最终的SQL查询是我所期望的:

print(
    s.query(Parcel)\
    .join(Subject, Parcel.sender_id == Subject.id)\
    .filter(Subject.name == 'Bob')
)

生成下一个SQL查询:

SELECT parcel.id AS parcel_id,
       parcel.sender_id AS parcel_sender_id,
       parcel.receiver_id AS parcel_receiver_id,
       subject_1.id AS subject_1_id,
       subject_1.name AS subject_1_name,
       subject_2.id AS subject_2_id,
       subject_2.name AS subject_2_name
FROM parcel
JOIN subject ON parcel.sender_id = subject.id
LEFT OUTER JOIN subject AS subject_1 ON subject_1.id = parcel.sender_id
LEFT OUTER JOIN subject AS subject_2 ON subject_2.id = parcel.receiver_id
WHERE subject.name = ?

在这里,您可以看到subject表正在连接三次而不是两次。这是因为senderreceiver关系都配置为加载加入。第三次加入是我过滤的主题。

我希望最终查询看起来像这样:

SELECT parcel.id AS parcel_id,
       parcel.sender_id AS parcel_sender_id,
       parcel.receiver_id AS parcel_receiver_id,
       subject_1.id AS subject_1_id,
       subject_1.name AS subject_1_name,
       subject_2.id AS subject_2_id,
       subject_2.name AS subject_2_name
FROM parcel
LEFT OUTER JOIN subject AS subject_1 ON subject_1.id = parcel.sender_id
LEFT OUTER JOIN subject AS subject_2 ON subject_2.id = parcel.receiver_id
WHERE subject_1.name = ?

我认为通过多个引用关系进行过滤不应该如此不清楚,并且有更好更清晰的方法。请帮我找到。

1 个答案:

答案 0 :(得分:1)

您已对其进行了配置,senderreciever将始终通过加入加入。
您可以更改它并手动执行joinedload,当您实际需要同时加入两个连接时加载它们。

如果您希望保留定义,可以“帮助”SQLAlchemy并指出查询已经包含了此比较的所有数据,并且不需要额外的连接。为此,使用contains_eager选项。

修改后的查询:

q = (s.query(Parcel)
     .join(Parcel.sender)
     .options(contains_eager(Parcel.sender))
     .filter(Subject.name == 'Bob'))

它产生的SQL:

SELECT subject.id AS subject_id,
       subject.name AS subject_name,
       parcel.id AS parcel_id,
       parcel.sender_id AS parcel_sender_id,
       parcel.receiver_id AS parcel_receiver_id,
       subject_1.id AS subject_1_id,
       subject_1.name AS subject_1_name
FROM parcel
JOIN subject ON subject.id = parcel.sender_id
LEFT OUTER JOIN subject AS subject_1 ON subject_1.id = parcel.receiver_id
WHERE subject.name = ?