简体   繁体   中英

Creating an sqlalchemy hybrid_property that allows for “in_” operator

How would you make a hybrid_property that allows the in_ clause? What would the SQLAlchemy expression look like?

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()

SQLAlchemy supports the + operator on expressions with type String , so you can cast your columns to String and then do something like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM