我是SQL Alchemy的新手。我正在尝试根据关系定义混合属性:
class Lead(Base):
__tablename__ = 'lead'
id = Column(Integer, primary_key=True)
assistant_id = Column(Integer, ForeignKey('assistant.id'))
legacy_assistant_id = Column(Integer, ForeignKey('legacy_assistant.id'))
assistant = relationship('Assistant')
legacy_assistant = relationship('LegacyAssistant')
@hybrid_property
def assistant_name(self):
if not self.assistant_id and not self.legacy_assistant_id:
return 'Unassigned'
elif not self.assistant_id and self.legacy_assistant_id:
return self.legacy_assistant.name
else:
return self.assistant.name
@assistant_name.expression
def assistant_name(cls):
return (
select(
case(
[
(cls.assistant_id == None, Assistant.name),
(and_(cls.assistant_id == None, cls.legacy_assistant_id == None), 'Unassigned'),
(and_(cls.assistant_id == None, cls.legacy_assistant_id != None), LegacyAssistant.name),
]
)
)
)
当我执行查询以获取assistant_name
属性时,我会以一种或另一种方式得到错误。这里有一些:
AttributeError while querying: Neither 'InstrumentedAttribute'
object nor 'Comparator' has an attribute
->当我只有
hybrid_property
而不是expression
columns argument to select()
must be a Python list or other iterable
->混合使用
使用表达式。 如何定义我的assistant_name
属性,该属性根据来自两个关系(assistant和legacy_assistant)的值得出其值?
谢谢!