Badr Fourane
Badr Fourane

Reputation: 23

ImportError when setting wagtail development environment : "cannot import name 'Query' from 'wagtail.search.models'"

I'm currently working on a fork of Wagtail (version 6.0a0) and attempting to set up a development environment for contributing to the project. I've followed the standard steps for setting up the project but have encountered an ImportError when running migrations for a Wagtail-based website.

Steps I've Taken:

Error Message:
Traceback (most recent call last):
    File "path/to/manage.py", line 10, in
        ...
        from wagtail.search.models import Query
ImportError: cannot import name 'Query' from 'wagtail.search.models'

Additional Information:

I at first thought this might be a dependency versions problem because the released version works fine with the Django 4.2 version, so I updated Django to 4.2 but the issue remained.

My questions:

Upvotes: 2

Views: 971

Answers (2)

Rich - enzedonline
Rich - enzedonline

Reputation: 1258

There's a deprecation warning regarding search:

RemovedInWagtail60Warning: The wagtailsearch.Query model has been moved to wagtail.contrib.search_promotions. Please update your code to use the Query model from that app instead.

And note in the 5.0 release notes: https://docs.wagtail.org/en/stable/releases/5.0.html#wagtailsearch-query-migration

Amend your import path to

from wagtail.contrib.search_promotions.models import Query

It generates a migration file after changing to this model

You also have to add wagtail.contrib.search_promotions to INSTALLED_APPS in your settings.

Upvotes: 5

gasman
gasman

Reputation: 25227

As noted in Rich's answer, the Query model (referenced in search/views.py in the initial project structure created by wagtail start) was moved from the wagtail.search module to wagtail.contrib.search_promotions in Wagtail 5.0. The old model was left in place until work began on Wagtail 6.0 a week or two ago.

Leaving the original import in place in the default project structure was a mistake, and I've now submitted a fix for this: https://github.com/wagtail/wagtail/pull/11190. Once this is fix is merged, bringing up a new project will work as intended.

In the meantime, you can patch the created project yourself - either change the import in search/views.py as Rich suggests, or remove it along with these two lines in the search function:

    query = Query.get(search_query)
    query.add_hit()

Alternatively, I'd recommend using bakerydemo as a test project for developing Wagtail against, rather than creating a new project from scratch - the relevant fix was applied to bakerydemo a while back.

Upvotes: 0

Related Questions