Я пытаюсь получить данные из эластичного поиска в моем приложении, но он возвращает набор запросов, который вызывает ошибку в моих сериализаторах "Expected a list of items but got type \"Search\"."
.И когда я печатаю результаты, полученные из упругого поиска, я получаю <django_elasticsearch_dsl.search.Search object at 0x1101f2b00>
.Раньше я не использовал эластичный поиск, и он дал мне ад ...
document.py
from django_elasticsearch_dsl import DocType, Index, fields
from elasticsearch_dsl import analyzer
from .models import Unit, Rental
units = Index('units')
html_strip = analyzer(
'html_strip',
tokenizer="standard",
filter=["standard", "lowercase", "stop", "snowball"],
char_filter=["html_strip"]
)
@units.doc_type
class UnitDocument(DocType):
rental = fields.ObjectField(properties={
'property_type': fields.TextField(),
'city': fields.TextField(),
})
class Meta:
model = Unit
fields = [
'bedroom',
'bathroom',
'price',
]
related_models = [Rental]
def get_queryset(self):
"""Not mandatory but to improve performance we can select related in one sql request"""
return super(UnitDocument, self).get_queryset().select_related(
'rental'
)
def get_instances_from_related(self, related_instance):
"""If related_models is set, define how to retrieve the unit instance(s) from the related model.
The related_models option should be used with caution because it can lead in the index
to the updating of a lot of items.
"""
if isinstance(related_instance, Rental):
return related_instance.car_set.all()
В моем файле views.py я попытался захватить ожидаемые данные.
views.py
class SearchView(APIView):
permission_classes = (AllowAny,)
def get(self, request):
query_price = request.query_params.get('budget')
query_bedroom = request.query_params.get('bed')
query_bathroom = request.query_params.get('bathroom')
query_city = request.query_params.get('city')
query_type = request.query_params.get('type')
query_obj = {
'price': query_price,
'city': query_city,
'bathroom': query_bathroom,
'bedroom': query_bedroom,
'property_type': query_type
}
if query_obj:
search_results = UnitDocument.search().query("match", price=query_price)
serializers = UnitSerializer(data=search_results, many=True)
if serializers.is_valid(raise_exception=True):
return Response(serializers.data, status=status.HTTP_200_OK)
else:
all_units = Unit.objects.all()
serializers = UnitSerializer(data=all_units)
if serializers.is_valid():
return Response(serializers.data, status=status.HTTP_200_OK)
setting.py
# Django Elasticsearch integration
'django_elasticsearch_dsl',
# Django REST framework Elasticsearch integration (this package)
'django_elasticsearch_dsl_drf',