Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

AttributeError: 'Query' object has no attribute 'msearch' #57

Closed
thisisashukla opened this issue Nov 26, 2021 · 8 comments
Closed

AttributeError: 'Query' object has no attribute 'msearch' #57

thisisashukla opened this issue Nov 26, 2021 · 8 comments

Comments

@thisisashukla
Copy link

thisisashukla commented Nov 26, 2021

Hi Team,
I am following the example given in the README for this repository. I am getting the following error message:

AttributeError: 'Query' object has no attribute 'msearch'

I am getting this on the following line:

results = Post.query.msearch(keyword,fields=['title'],limit=20).filter(...)

Thanks for any help on this.

@thisisashukla thisisashukla changed the title AttributeError: 'Query' object has no attribute 'search' AttributeError: 'Query' object has no attribute 'msearch' Nov 26, 2021
@honmaple
Copy link
Owner

Whether the app has been initialized?using Search(app) or search.init_app(app)

self.db.Model.query_class = self._query_class(self.db.Model.query_class)

@FatalX2080
Copy link

FatalX2080 commented Jun 21, 2023

Hi, so what happened next? Does the error fixed?
I have this problem too; And me use this for "search" init:

db = flask_sqlalchemy.SQLAlchemy()
search = Search(app, db=db)
search.init_app(app)
search.create_index(update=True)
MSEARCH_INDEX_NAME = "whoosh"
MSEARCH_PRIMARY_KEY = 'id'
MSEARCH_ENABLE = True

Request:

    db_sess = db_session.create_session()
    posts = db_sess.query(Post).msearch("ax", fields=['title', 'content'])

Error:

Traceback (most recent call last):
  File "", line 2551, in __call__
    return self.wsgi_app(environ, start_response)
  File "", line 2531, in wsgi_app
    response = self.handle_exception(e)
  File "", line 2528, in wsgi_app
    response = self.full_dispatch_request()
  File "", line 1825, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "", line 1823, in full_dispatch_request
    rv = self.dispatch_request()
  File "", line 1799, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
  File "", line 50, in fiend_results
    posts = db_sess.query(Post).msearch("ax", fields=['title', 'content'])
AttributeError: 'Query' object has no attribute 'msearch'

and yah, backends.py has this line

@honmaple
Copy link
Owner

@FatalX2080 Please show the version offlask and flask_sqlalchemy, or print info with

print([i for i in dir(db_sess.query(Post)) if not i.startswith("_")])
print([i for i in dir(Post.query) if not i.startswith("_")])

@FatalX2080
Copy link

@honmaple First line return this:

['add_column', 'add_columns', 'add_entity', 'all', 'allows_lambda', 'apply_labels', 'as_scalar', 'autoflush', 'column_descriptions', 'correlate', 'count', 'cte', 'delete', 'dispatch', 'distinct', 'enable_assertions', 'enable_eagerloads', 'except_', 'except_all', 'execution_options', 'exists', 'filter', 'filter_by', 'first', 'from_statement', 'get', 'get_children', 'get_execution_options', 'get_label_style', 'group_by', 'having', 'instances', 'intersect', 'intersect_all', 'is_delete', 'is_dml', 'is_insert', 'is_select', 'is_single_entity', 'is_text', 'is_update', 'join', 'label', 'lazy_loaded_from', 'limit', 'load_options', 'logger', 'logging_name', 'memoized_attribute', 'memoized_instancemethod', 'merge_result', 'offset', 'one', 'one_or_none', 'only_return_tuples', 'options', 'order_by', 'outerjoin', 'params', 'populate_existing', 'prefix_with', 'reset_joinpoint', 'scalar', 'scalar_subquery', 'select_from', 'selectable', 'session', 'set_label_style', 'slice', 'statement', 'subquery', 'suffix_with', 'supports_execution', 'tuples', 'union', 'union_all', 'update', 'uses_inspection', 'value', 'values', 'where', 'whereclause', 'with_entities', 'with_for_update', 'with_hint', 'with_labels', 'with_parent', 'with_session', 'with_statement_hint', 'with_transformation', 'yield_per']

Second:

Traceback (most recent call last):
  File "", line 2551, in __call__
    return self.wsgi_app(environ, start_response)
  File "", line 2531, in wsgi_app
    response = self.handle_exception(e)
  File "", line 2528, in wsgi_app
    response = self.full_dispatch_request()
  File "", line 1825, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "", line 1823, in full_dispatch_request
    rv = self.dispatch_request()
  File "", line 1799, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
  File "", line 51, in fiend_results
    print([i for i in dir(Post.query) if not i.startswith("_")])
AttributeError: type object 'Post' has no attribute 'query'

Versions:
Flask - 2.2.3
Flask-SQLAlchemy - 3.0.4

P.s. I think, will better if I add class model:

class Post(dbase):
    __tablename__ = 'post'
    __searchable__ = ['title', 'content']
    id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True, autoincrement=True)
    title = sqlalchemy.Column(sqlalchemy.String)
    content = sqlalchemy.Column(sqlalchemy.Text)
    user = orm.relationship('User', backref='articles')
    user_id = sqlalchemy.Column(sqlalchemy.Integer, sqlalchemy.ForeignKey('users.id'))

    def __repr__(self):
        return '<Post:{}>'.format(self.title)

@honmaple
Copy link
Owner

@FatalX2080 dbbase is db.Model's subclass? Please check db.Model.query_class is

<class 'flask_sqlalchemy.BaseQuery'>

or

<class 'flask_msearch.whoosh_backend.WhooshSearch._query_class.<locals>.Query'>

@honmaple
Copy link
Owner

@FatalX2080

search = Search(app, db=db)
search.init_app(app)

Don't initialize app multi times.

@FatalX2080
Copy link

@honmaple

import sqlalchemy.ext.declarative as dec
dbase = dec.declarative_base()

@honmaple
Copy link
Owner

@FatalX2080 For quick fixed, use

from flask_sqlalchemy import BaseQuery


class QueryClass(BaseQuery):
    msearch = None


db = SQLAlchemy(app, query_class=QueryClass)
search = Search(app, db=db)

QueryClass.msearch = db.Model.query_class.msearch

If you use custom session rather than db.session, please use

session_options = {"query_cls": QueryClass}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants