我正在尝试在我的应用程序中从Elasticsearch获取数据,但它返回一个查询集,这会在我的序列化器中触发错误,错误信息为
document.py
在我的views.py文件中,我尝试捕获预期的数据。
视图.py
"Expected a list of items but got type \"Search\"."
。当我打印从Elasticsearch返回的结果时,我得到了<django_elasticsearch_dsl.search.Search object at 0x1101f2b00>
。我以前没有使用过Elasticsearch,现在感到很困惑。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文件中,我尝试捕获预期的数据。
视图.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',