Skip to content
Advertisement

SearchFilter for multiple models — Django

Using Django 3.2 with Restframework. I’m 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:

Views.py

JavaScript

In here, while printing the output it does print a json object, but doesn’t return anything as output. Any cause why there is no output, where am I doing wrong?

serializers.py

JavaScript

Also I tried with serializers.ModelSerializer but it will only accept 1 model in serializer. Any suggestions please!

Edit: On testing in Postman I received following output:

Endpoint: localhost:8000/search/?query=john

JavaScript

Expected outcome:

JavaScript

To reproduce, console gives output: [<MasterUser: abc@xyz.com>, <MasterUser: dummy2@xyz.com>]

As the firstname has John the whole MasterUser came as output.

Advertisement

Answer

Eventually I get rid of class GlobalSearchList(generics.ListAPIView): and also its serializers.

and just add response as return HttpResponse(serialize_obj,content_type='application/json') to receive json response.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement