如何编写带有case语句的混合属性?

时间:2019-09-18 23:52:09

标签: python orm sqlalchemy

我是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属性时,我会以一种或另一种方式得到错误。这里有一些:

  1. AttributeError while querying: Neither 'InstrumentedAttribute' object nor 'Comparator' has an attribute->当我只有 hybrid_property而不是expression
  2. columns argument to select() must be a Python list or other iterable->混合使用 使用表达式。
  3. 依此类推...

如何定义我的assistant_name属性,该属性根据来自两个关系(assistant和legacy_assistant)的值得出其值? 谢谢!

0 个答案:

没有答案