BDuelz
BDuelz

Reputation: 3928

Find class being queried on from custom Query class in SQLAlchemy?

I'm currently doing something like this in 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))

I want to set up a custom query class and do something like:

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)

It just seems cleaner to me. I also have other use cases for needing to know what class is being queried -- for instance, a series of Notification classes in which I need to know what notification type to return.

Is there any way to find out what class is being queried from inside BaseQuery.fulltext?

Upvotes: 2

Views: 265

Answers (1)

sayap
sayap

Reputation: 6277

This should work:

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

Upvotes: 5

Related Questions