Searching in multiple models' tables in Django Rest Framework

Viewed 2255

I have 3 tables

  • PC(ID, PcNAME, Brand)
  • CellPhoness(ID, CellPhoneName, Brand)
  • Printers(ID, PrinterName, Brand).

There is no relationship between the 3 tables. I would like to run a query where the user can input the search string and the program will search the 3 models for where the data exists and return the same with the Id, name, and brand in the form of a JSON response.

1 Answers

You can do something like this:

  1. Get query text from query params

  2. Filter based on it

  3. Return serializer data

     def view(request):
         query = request.GET.get("query", None)
         pcs = PC.objects.all()
         cell_phones = CellPhone.objects.all()
         printers = Printer.objects.all()
    
         if query:
             pcs = pcs.filter(name__icontains=query)
             cell_phones = cell_phones.filter(name__icontains=query)
             printers = printers.filter(name__icontains=query)
    
         return JsonResponse({"pcs": PCSerializer(instances=pcs, many=True).data,
                             "cell_phones": CellPhoneSerializer(instances=cell_phones, many=True).data,
                             "printers": PrinterSerializer(instances=printers, many=True).data})
    

You'll need to create serializers for each objects, please have a look at this documentation.

Related