【django学习-22】列表界面搜索功能

  • 1.需求:靓号列表界面,根据手机号码模糊匹配
  • 2.前端传search_data
<div style="float: right;width: 300px;">
    <form method="get">
        <div class="input-group">
            <input type="text" name="q" class="form-control" placeholder="Search for..."
                   value="{{ search_data }}">
            <span class="input-group-btn">
            <button class="btn btn-default" type="submit">
                <span class="glyphicon glyphicon-search" aria-hidden="true"></span>
            </button>
          </span>
        </div>
    </form>
</div>
  • 3.后台根据search_data模糊匹配手机号
from app01.utils.pagination import Pagination
from app01.utils.form import UserModelForm, PrettyModelForm, PrettyEditModelForm


def pretty_list(request):
    """ 靓号列表 """

    data_dict = {}
    search_data = request.GET.get('q', "")
    if search_data:
        data_dict["mobile__contains"] = search_data

    queryset = models.PrettyNum.objects.filter(**data_dict).order_by("-level")
    context = {
        "search_data": search_data,
        "queryset": queryset, 
  
    }
    return render(request, 'pretty_list.html', context)

  • 4.扩展
# 多条件搜索
models.PrettyNum.objects.filter(mobile="19999999991",id=12)
data_dict = {"mobile":"19999999991","id":123}
models.PrettyNum.objects.filter(**data_dict)

models.PrettyNum.objects.filter(id=12)       # 等于12
models.PrettyNum.objects.filter(id__gt=12)   # 大于12
models.PrettyNum.objects.filter(id__gte=12)  # 大于等于12
models.PrettyNum.objects.filter(id__lt=12)   # 小于12
models.PrettyNum.objects.filter(id__lte=12)  # 小于等于12
data_dict = {"id__lte":12}
models.PrettyNum.objects.filter(**data_dict)

models.PrettyNum.objects.filter(mobile="999")               # 等于
models.PrettyNum.objects.filter(mobile__startswith="1999")  # 筛选出以1999开头
models.PrettyNum.objects.filter(mobile__endswith="999")     # 筛选出以999结尾
models.PrettyNum.objects.filter(mobile__contains="999")     # 筛选出包含999
data_dict = {"mobile__contains":"999"}
models.PrettyNum.objects.filter(**data_dict)
posted @ 2024-05-13 22:55  Tony_xiao  阅读(21)  评论(0编辑  收藏  举报