Click here to Skip to main content
15,747,911 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Using Django 3.2 with Restframework. Im trying for search filter and create a API with restframework which would output the searched term with its whole object.

I had a little success on that with official doc. But from that I can only search in a single Model and not as globally. I found a blog on how to use multiple Models together?

I tried for following from that:

What I have tried:

<pre lang="Python">
class GlobalSearchList(generics.ListAPIView):
    serializer_class = GlobalSearchSerializer

    def get_queryset(self):
      query = self.request.query_params.get('query', None)
      users = MasterUser.objects.filter(Q(firstname__icontains=query) | Q(lastname__icontains=query) | Q(email__icontains=query) | Q(category__icontains=query))
      webinar = MasterWebinar.objects.filter(Q(host__icontains=query) | Q(title__icontains=query))
      section = ResourceSection.objects.filter(Q(resource_name__icontains=query))
      item = SectionItem.objects.filter(Q(item_title__icontains=query))
      all_results = list(chain(users,webinar,section,item))
      serialize_obj = serializers.serialize('json',all_results)
      print(serialize_obj)    #Json response is printed in console
      return JsonResponse(json.loads(serialize_obj), safe=False)   #nothing as output
<pre lang="Python">
class GlobalSearchSerializer(serializers.Serialize):
    def to_native(self, obj):
        if isinstance(obj, MasterIndividualMembers): 
            serializer = MasterIndividualMembersSerializer(obj)
        elif isinstance(obj, MasterUser):
            serializer = MasterUserSerializer(obj)
         elif isinstance(obj, MasterWebinar):
             serializer = MasterWebinarSerializer(obj)
         elif isinstance(obj, MasterResource):
             serializer = MasterResourceSerializer(obj)
         elif isinstance(obj, ResourceSection):
             serializer = ResourceSectionSerializer(obj)
         elif isinstance(obj, SectionItem):
             serializer = SectionItemSerializer(obj)

            raise Exception("Not found in any instance!")

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900