1. 条件搜索

使用条件搜索时,可以直接使用filter链来过滤掉满足条件的记录,因为每次filter()的结果仍然是一个QuerySet,因此可以根据参数有无,来添加filter。
先不添加任何搜索条件获取一个QuerySet。

  1. invoice_heads = InvoiceHead.objects.filter(
  2. resource_uid=resource_uid,
  3. status="Y",
  4. user_id=user_id,)

1) 等值比较

  1. if invoice_type is not None:
  2. invoice_heads = invoice_heads.filter(invoice_type=invoice_type)

2) 不等于比较

大于等于gte, 小于等于lte。

  1. if end_date is not None:
  2. invoice_heads = invoice_heads.filter(invoice_date__lte=end_date)

3) 完整案例

将每个需要搜索的字段先判断一下是不是None,如果不是None,那么就在queryset后面在拼接.filter() ,实现条件搜索过滤。

  1. class OpenedInvoiceQuery(BaseView):
  2. def get(self, request, resource_uid=None):
  3. r = Result()
  4. using = self.get_partner(request)
  5. try:
  6. student = self.student_auth(request)
  7. user_id = student['id']
  8. invoice_type = request.GET.get("invoice_type")
  9. invoice_code = request.GET.get("invoice_code")
  10. invoice_no = request.GET.get("invoice_no")
  11. start_date = request.GET.get("start_date")
  12. end_date = request.GET.get("end_date")
  13. invoice_status = request.GET.get("invoice_status", 0)
  14. size = int(request.GET.get("size", 10))
  15. page = int(request.GET.get("page", 0))
  16. invoice_heads = InvoiceHead.objects.filter(
  17. resource_uid=resource_uid,
  18. status="Y",
  19. user_id=user_id,
  20. )
  21. if invoice_type is not None:
  22. invoice_heads = invoice_heads.filter(invoice_type=invoice_type)
  23. if invoice_code is not None:
  24. invoice_heads = invoice_heads.filter(invoice_code=invoice_code)
  25. if invoice_no is not None:
  26. invoice_heads = invoice_heads.filter(invoice_no=invoice_no)
  27. if invoice_status is not None:
  28. invoice_heads = invoice_heads.filter(red_flag=invoice_status)
  29. if start_date is not None:
  30. invoice_heads = invoice_heads.filter(invoice_date__gte=start_date)
  31. if end_date is not None:
  32. invoice_heads = invoice_heads.filter(invoice_date__lte=end_date)
  33. r.data_count = len(invoice_heads)
  34. page_obj = Paginator(invoice_heads, size)
  35. page_data = page_obj.get_page(page)
  36. res = page_data.object_list
  37. data = []
  38. for i in res:
  39. d = InvoiceHeadSerializers(i).data
  40. line = InvoiceLine.objects.filter(head=i).first()
  41. d["main_goods_name"] = line.goods_name
  42. d["total_price_with_tax"] = i.amount + i.total_amount
  43. data.append(d)
  44. r.data = data
  45. except Exception as e:
  46. r.error(e)
  47. return self.s_result(r)

2. 模糊匹配

django的orm中,可以使用__icontains 来表示mysql里的like “%%”
匹配code,key,goods_name,simple_name:

  1. from django.db.models import Q
  2. row = InvoiceProductCategories.objects.using("admin") \
  3. .filter(~Q(rate1=None),
  4. goods_name__icontains=goods_name,
  5. simple_name__icontains=simple_name,
  6. code__icontains=code,
  7. key__icontains=key)

不等于使用~Q,在默认的不等于None中,需要把~Q放到filter()的最前面,要不然会编译不通过。