Skip to main content
 首页 » 编程设计

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

2024年12月31日17rubylouvre

我有3张 table

  • PC(ID、PcNAME、品牌)
  • CellPhones(ID, CellPhoneName, Brand)
  • 打印机(ID、打印机名称、品牌)。

3个表之间没有任何关系。我想运行一个查询,用户可以在其中输入搜索字符串,程序将搜索 3 个模型以查找数据所在的位置,并以 JSON 响应的形式返回相同的 ID、名称和品牌。

请您参考如下方法:

你可以这样做:

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

您需要为每个对象创建序列化程序,请查看 this documentation .