在Django Rest Framework中搜索多个模型的表

时间:2018-12-17 06:10:42

标签: python django django-models django-rest-framework

我有3个表 PC(ID,PcNAME,Brand) CellPhoness(ID,CellPhoneName,Brand)打印机(ID,PrinterName,Brand) 。这三个表之间没有关系。我想在用户可以输入搜索字符串的地方运行查询,程序将在3个模型中搜索数据的存在位置,并以JSON响应的形式返回ID,名称和品牌。

2 个答案:

答案 0 :(得分:2)

The above answer lacks curly braces in the dictionary resulting the error.  
Just added braces in the above code.  

 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})

答案 1 :(得分:1)

您可以执行以下操作:

  1. 从查询参数中获取查询文本
  2. 基于它的过滤器
  3. 返回序列化器数据

    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)
    

您需要为每个对象创建序列化器,请查看此https://www.django-rest-framework.org/api-guide/serializers/