python - 在 SQLAlchemy 中从自定义查询类中查找正在查询的类?

标签 python sqlalchemy polymorphism

我目前正在 SQLA 中做类似的事情:

class Base(object):
    query = DBSession.query_property()
    @classmethod
    def _get_fulltext_query(cls, terms):
        # Search is a method which runs a fulltext search in Whoosh for objects of the given type, returning all ids which match the given terms
        ids = search(terms, cls.__name__)
        return cls.query.filter(cls.id.in_(ids))

我想设置一个自定义查询类并执行以下操作:

class BaseQuery(Query):
    def fulltext(self, terms):
        # Need a way to find out what class we're querying so that I can run the fulltext search and return the proper query

class Base(object):
    query = DBSession.query_property(BaseQuery)

对我来说,它看起来更干净。我还有其他用例需要知道正在查询什么类 - 例如,一系列通知类,我需要知道要返回什么通知类型。

有什么方法可以找出从 BaseQuery.fulltext 内部查询的类是什么?

最佳答案

这应该有效:

class BaseQuery(Query):
    def fulltext(self, terms):
        # assuming query is always created with `cls.query` or `DBSession.query(cls)`
        cls = self._entities[0].type
        ...

关于python - 在 SQLAlchemy 中从自定义查询类中查找正在查询的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12253877/

相关文章:

python | Pandas |读取不同格式的 Excel 表格

Python回车和线程

python - TensorFlow 2.0 凯拉斯 : How to write image summaries for TensorBoard

c++ - 为什么这个虚方法返回真?

python - 如何在Python中拥有一个万能的函数调用,可以调用不同的函数?

postgresql - 通过 EC2 从 sqlalchemy 连接 AWS RDS

python - 在 SQLAlchemy 中使用序列生成字符串主键

java - 使用 Jackson 通过 @JsonUnwrapped 反序列化多态类型

go - 如何制作一个接收自定义接口(interface)数组的函数

python - 将一个类映射到 SQLAlchemy 中的多个表