创建一个sqlalchemy hybrid_property,允许“in_”运算符

时间:2018-04-23 22:23:27

标签: python orm sqlalchemy

你如何制作允许in_条款的hybrid_property? SQLAlchemy expression会是什么样的?

class Version(Base):
    version_id = Column(Integer, primary_key=True)
    package_id = Column(Integer, ForeignKey('package.package_id')
    version = Column(String(32), index=True)

    @hybrid_property
    def pkg_id_concat_vers(self):
        # "23~~0.2.4"
        return "{}~~{}".format(self.package_id, self.version)

# TODO
#@pkg_id_concat_vers(self):
#    pass

# Using the naive `(not) in` doesn't actually apply the filter
data = ['23~~0.2.4', '57~~0.0.1']
result = (session.query(Version)
          .filter(Version.pkg_id_concat_vers in data)
          ).all()

# Using `in_()` throws an Attribute Error, as it's a string.
data = ['23~~0.2.4', '57~~0.0.1']
result = (session.query(Version)
          .filter(Version.pkg_id_concat_vers.in_(data))
          ).all()

1 个答案:

答案 0 :(得分:2)

SQLAlchemy支持var q = qstr + "&p=" + pstr; 类型为+的表达式的String运算符,因此您可以将列转换为String,然后执行以下操作:

@pkg_id_concat_vers.expression
def pkg_id_concat_vers(cls):
    return cast(cls.package_id, String) + "~~" + cast(cls.version, String)