In Django elastic search DocumentViewSet, I want to override get_queryset such that queryset = queryset OR (id=1)

26 Views Asked by At

In Django elastic search DocumentViewSet, I want to override get_queryset such that queryset = queryset OR (id=1) I want the results of original queryset along with records of id=addids

from django.db.models import Q

class YourElasticsearchView(DocumentViewSet):
    # Your other view settings...

    def get_queryset(self):
        queryset = super().get_queryset()

        # Get the field from the query parameters
        ids_param = self.request.query_params.get('addids')

        if ids_param is not None:
            ids = [int(id_) for id_ in ids_param.split(',')]  # Convert to integers

            # Construct an OR query
            or_query = Q(id__in=ids) | Q(queryset.query)

            # Update the queryset to include records satisfying either condition
            queryset = queryset.filter(or_query)

        return queryset
I also tried like this:
            if ids_param is not None:
                ids = ids_param.split(',')
                 # Construct an OR query for document IDs
                id_query = Q('terms', **{'id': ids})
                 # Create a bool query with should clauses
                or_query = Q('bool', should=[id_query,queryset.query], minimum_should_match=1)
                search = Search(index='indexname')
                queryset = search.query(or_query)
           return queryset

For example, original query set is giving 3 records (id=1,2,3).

addids=5,6,7,8

I want total 7 records including query results, and addids results.

0

There are 0 best solutions below