1. 条件搜索
使用条件搜索时,可以直接使用filter链来过滤掉满足条件的记录,因为每次filter()的结果仍然是一个QuerySet,因此可以根据参数有无,来添加filter。
先不添加任何搜索条件获取一个QuerySet。
invoice_heads = InvoiceHead.objects.filter(
resource_uid=resource_uid,
status="Y",
user_id=user_id,)
1) 等值比较
if invoice_type is not None:
invoice_heads = invoice_heads.filter(invoice_type=invoice_type)
2) 不等于比较
大于等于gte, 小于等于lte。
if end_date is not None:
invoice_heads = invoice_heads.filter(invoice_date__lte=end_date)
3) 完整案例
将每个需要搜索的字段先判断一下是不是None,如果不是None,那么就在queryset后面在拼接.filter() ,实现条件搜索过滤。
class OpenedInvoiceQuery(BaseView):
def get(self, request, resource_uid=None):
r = Result()
using = self.get_partner(request)
try:
student = self.student_auth(request)
user_id = student['id']
invoice_type = request.GET.get("invoice_type")
invoice_code = request.GET.get("invoice_code")
invoice_no = request.GET.get("invoice_no")
start_date = request.GET.get("start_date")
end_date = request.GET.get("end_date")
invoice_status = request.GET.get("invoice_status", 0)
size = int(request.GET.get("size", 10))
page = int(request.GET.get("page", 0))
invoice_heads = InvoiceHead.objects.filter(
resource_uid=resource_uid,
status="Y",
user_id=user_id,
)
if invoice_type is not None:
invoice_heads = invoice_heads.filter(invoice_type=invoice_type)
if invoice_code is not None:
invoice_heads = invoice_heads.filter(invoice_code=invoice_code)
if invoice_no is not None:
invoice_heads = invoice_heads.filter(invoice_no=invoice_no)
if invoice_status is not None:
invoice_heads = invoice_heads.filter(red_flag=invoice_status)
if start_date is not None:
invoice_heads = invoice_heads.filter(invoice_date__gte=start_date)
if end_date is not None:
invoice_heads = invoice_heads.filter(invoice_date__lte=end_date)
r.data_count = len(invoice_heads)
page_obj = Paginator(invoice_heads, size)
page_data = page_obj.get_page(page)
res = page_data.object_list
data = []
for i in res:
d = InvoiceHeadSerializers(i).data
line = InvoiceLine.objects.filter(head=i).first()
d["main_goods_name"] = line.goods_name
d["total_price_with_tax"] = i.amount + i.total_amount
data.append(d)
r.data = data
except Exception as e:
r.error(e)
return self.s_result(r)
2. 模糊匹配
在django的orm中,可以使用__icontains 来表示mysql里的like “%%”
匹配code,key,goods_name,simple_name:
from django.db.models import Q
row = InvoiceProductCategories.objects.using("admin") \
.filter(~Q(rate1=None),
goods_name__icontains=goods_name,
simple_name__icontains=simple_name,
code__icontains=code,
key__icontains=key)
不等于使用~Q,在默认的不等于None中,需要把~Q放到filter()的最前面,要不然会编译不通过。