Я получаю AttributeError:
(AttributeError at /search/
'QuerySet' object has no attribute 'facet') while setting up custom filters for django-taggit tags with Haystack
Функция поиска работает нормально, когда я ввожу запрос следующим образом:
http://localhost:8000/search/?q=las+vegas
Но ошибка появляется, когда я пытаюсь добавить другую переменную для фильтра ptags, например: http://localhost:8000/search/?q=las+vegas&ptags=Solo
Как я могу решить эту проблему?
Полный вывод:
20:56:46 Django version 1.10.5, using settings 'uvergo.settings'
Starting development server at http://127.0.0.1:8000/ Quit the server
with CTRL-BREAK. Internal Server Error: /search/ Traceback (most
recent call last): File
"C:\Users\loicq\desktop\coding\uvergo_search\venv\lib\site-packages\django\core\handlers\exception.py",
line 39, in inner
response = get_response(request) File "C:\Users\loicq\desktop\coding\uvergo_search\venv\lib\site-packages\django\core\handlers\base.py",
line 187, in _get_response
response = self.process_exception_by_middleware(e, request) File "C:\Users\loicq\desktop\coding\uvergo_search\venv\lib\site-packages\django\core\handlers\base.py",
line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\loicq\desktop\coding\uvergo_search\venv\lib\site-packages\django\views\generic\base.py",
line 68, in view
return self.dispatch(request, *args, **kwargs) File "C:\Users\loicq\desktop\coding\uvergo_search\venv\lib\site-packages\django\views\generic\base.py",
line 88, in dispatch
return handler(request, *args, **kwargs) File "C:\Users\loicq\desktop\coding\uvergo_search\venv\lib\site-packages\haystack\generic_views.py",
line 120, in get
form = self.get_form(form_class) File "C:\Users\loicq\desktop\coding\uvergo_search\venv\lib\site-packages\django\views\generic\edit.py",
line 45, in get_form
return form_class(**self.get_form_kwargs()) File "C:\Users\loicq\Desktop\Coding\UVERGO_SEARCH\venv\src\search\views.py",
line 47, in get_form_kwargs
kwargs = super().get_form_kwargs() File "C:\Users\loicq\desktop\coding\uvergo_search\venv\lib\site-packages\haystack\generic_views.py",
line 94, in get_form_kwargs
kwargs = super(FacetedSearchMixin, self).get_form_kwargs() File "C:\Users\loicq\desktop\coding\uvergo_search\venv\lib\site-packages\haystack\generic_views.py",
line 65, in get_form_kwargs
kwargs.update({'searchqueryset': self.get_queryset()}) File "C:\Users\loicq\desktop\coding\uvergo_search\venv\lib\site-packages\haystack\generic_views.py",
line 108, in get_queryset
qs = qs.facet(field) AttributeError: 'QuerySet' object has no attribute 'facet' [02/May/2019 20:57:04] "GET
/search/?q=las+vegas&ptags=Solo HTTP/1.1" 500 97950 ```
Models.py
class Product(models.Model):
title = models.CharField(max_length=255, default='')
slug = models.SlugField(null=True, blank=True, unique=True, max_length=255, default='')
ptags = TaggableManager()
image = models.ImageField(default='')
timestamp = models.DateTimeField(auto_now=True)
def _ptags(self):
return [t.name for t in self.ptags.all()]
def get_absolute_url(self):
return reverse('product',
kwargs={'slug': self.slug})
def __str__(self):
return self.title
Мой заказ forms.py
:
from haystack.forms import FacetedSearchForm
from django.db.models.query import QuerySet
#from haystack.query import SearchQuerySet
class FacetedProductSearchForm(FacetedSearchForm):
def __init__(self, *args, **kwargs):
self.request = kwargs.pop("request", None)
data = dict(kwargs.get("data", []))
super(FacetedProductSearchForm, self).__init__(*args, **kwargs)
def search(self):
sqs = super(FacetedProductSearchForm, self).search()
ptags = self.request.GET.get('ptags', None)
if ptags:
ptags = ptags.split(',')
sqs = self.queryset.filter(ptags__name__in=ptags).distinct()
return sqs:
Я передаю пользовательские формы в представлениях следующим образом:
class FacetedSearchView(BaseFacetedSearchView):
form_class = FacetedProductSearchForm
queryset = Product.objects.all()
facet_fields = ['ptags']
template_name = 'search_result.html'
paginate_by = 6
context_object_name = 'object_list'
def get_form_kwargs(self):
kwargs = super().get_form_kwargs()
kwargs["request"] = self.request
return kwargs
Urls:
from django.conf.urls import url
from django.contrib import admin
from search.views import HomeView, ProductView, FacetedSearchView, autocomplete
from .settings import MEDIA_ROOT, MEDIA_URL
from django.conf.urls.static import static
urlpatterns = [
url(r'^$', HomeView.as_view()),
url(r'^admin/', admin.site.urls),
url(r'^product/(?P<slug>[\w-]+)/$', ProductView.as_view(), name='product'),
url(r'^search/autocomplete/$', autocomplete),
url(r'^search/', FacetedSearchView.as_view(), name='haystack_search'),
] + static(MEDIA_URL, document_root=MEDIA_ROOT)