django 多字段可选查询

2023-02-18 14:28:13 浏览数 (1)

重点是使用字典传值查询。可以指定字段,且是字典为非必填。字段有值就查,没有值就不查该字段。

代码语言:javascript复制
@login_required(login_url="/user/login")
def my_earn(request):
    """
    我的收益,就是主播的流水
    :param request:
    :return:
    """
    title = "我的主播流水"
    description = "列出你所有的主播流水记录"
    if request.method == "POST" and request.POST:
        user_id = request.POST.get("user_id", None)
        # print(user_id.strip())
        start_time = request.POST.get("start_time", None)
        end_time = request.POST.get("end_time", None)
        search_dict = {
            "proportion_rule__agent": request.user
        }
        if user_id:
            search_dict["bill__anchor__user_id"] = user_id.strip()
        if start_time:
            search_dict["bill__live_day__gte"] = start_time
        if end_time:
            search_dict["bill__live_day__lte"] = end_time
        # print(search_dict)
        earns = BindBill.objects.order_by("-id").filter(**search_dict)
    else:
        earns = BindBill.objects.order_by("-id").filter(proportion_rule__agent=request.user)

    paginator = Paginator(earns, settings.PAGINATOR_PER_PAGE)
    page = request.GET.get('page')
    try:
        contents = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        contents = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        contents = paginator.page(paginator.num_pages)

    return render(request, "my_earn.html", locals())

0 人点赞