如何从elasticsearch django返回的查询集中获取数据

3
我正在尝试在我的应用程序中从Elasticsearch获取数据,但它返回一个查询集,这会在我的序列化器中触发错误,错误信息为"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',

我认为你需要额外的一步,将ES结果转换为查询集。 - rurp
你做错了。请阅读django-elasticsearch-dsl-drf文档,特别是ViewSet定义部分 - Artur Barseghyan
2个回答

1

search_results.to_queryset() 应该可以正常工作,search_result 是一个可迭代对象,返回具有模型字段的字典,它不是一个查询集,您也可以尝试使用 list(search_result),但我不确定。


0

回答需要支持信息 您的回答可以通过提供更多的支持信息来改进。请[编辑]以添加进一步的细节,例如引用或文档,以便他人可以确认您的回答是否正确。您可以在帮助中心找到关于如何撰写良好回答的更多信息。 - moken

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接