【发布时间】:2014-04-24 22:18:43
【问题描述】:
我有三个具有继承和关系的模型,我想缓存对这些模型的查询。
class Person(Base):
__tablename__ = 'person'
id = Column(Integer, primary_key=True)
name = Column(String(100), nullable=False)
type = Column(String(50))
__mapper_args__ = {
'polymorphic_identity': 'object',
'polymorphic_on': type
}
class Man(Person):
__tablename__ = 'man'
id = Column(Integer, ForeignKey('person.id'), primary_key=True)
age = Column(String(100), nullable=False)
__mapper_args__ = {'polymorphic_identity': 'man'}
class Config(Base):
__tablename__ = "config"
id = Column(Integer, primary_key=True)
person = Column(Integer, ForeignKey('person.id'))
address = Column(String)
person_ref = relationship(Person)
还有很多其他模型继承自Personal。 例如,我需要通过 Config 关系访问 Man 属性。 通常我会这样做:
config = session.query(Config).join(Config.person_ref).filter(Person.type == 'man').first()
print config.person_ref.age
如何使用 dogpile 缓存这样的查询? 我可以缓存查询到Config,但我不能缓存查询到Man的属性,每次都发出SQL。 我尝试使用 with_polymorphic,但它只能在没有连接负载的情况下使用。 (不明白为什么)
config = session.query(Config).options(FromCache("default")).first()
people = session.query(Person).options(FromCache("default")).with_polymorphic('*').get(config.person)
但我需要 joinload 来过滤类型。
【问题讨论】:
-
定义“不能”。堆栈跟踪?没有结果?每次都发出SQL?不清楚。
-
每次都发出 SQL。
-
不确定,您需要查看调用查询时生成的缓存键。使用 pdb.set_trace() 逐步了解正在发生的事情。缓存并不简单,这就是为什么这不是内置功能的原因;通过将其作为食谱来鼓励用户逐步完成它。
-
@zzzeek 你认为它应该如何工作?当我使用 joined 时,它只加入 Person 表,当我尝试访问 Man 属性时,SQL 发出,因为继承对象的属性延迟加载.
-
如果你想缓存延迟加载的属性,你有两个选择:1.使用joinedload()或2.使用在dogpile示例中也说明的RelationshipCache特性。
标签: python sqlalchemy dogpile.cache