django-filter和普通查询的例子
pythong在使用中,尤其是django的查询过程中插件还是不少的,最近发现了一个插件django-filter,还挺好用的
1.最原始直接根据条件查询
defsearch(request): request.encoding='utf-8' if'platform_order_code'inrequest.POST: code=request.POST['platform_order_code'] q1=Q(code__contain=code) sale_orders=SaleOrder.objects.filter(q1) response=TemplateResponse(request,'ofc/saleorder_manage.html', { "savorier":sale_orders, }) returnresponse
2、djamgo-filter插件查询,根据filter中的查询条件自动生成查询的额对话框,文本框,下拉框等;
(https://django-filter.readthedocs.io/en/master/guide/install.html)
defquery_saleorder(request): today=datetime.datetime.now() start_today=datetime.datetime(today.year,today.month,today.day,0,0,0) sale_orders=SaleOrder.objects.filter(create_time__gt=start_today) my_param=request.GET.get('status') #如果有参数,则从所有订单中筛选 if(my_param): filter=SaleOrderFilter(request.GET,queryset=SaleOrder.objects.all()) #如果没有参数的,则默认查询今天的 else: filter=SaleOrderFilter(request.GET,queryset=sale_orders) #filter=SaleOrderFilter(request.GET,queryset=SaleOrder.objects.all()) menus=SysPermission.objects.using("DB2").filter(level=1)[0:5] returnrender(request,'ofc/list.html',{'filter':filter,"menus":menus})
对应的filter.py的处理
widget可以给对应的生成的空间添加class等样式
importdjango_filters fromdjangoimportforms fromdjango.db.modelsimportQ fromofc.enumimportSTATUS_ENUM fromofc.modelsimportSaleOrder fromofc.utilsimportcode_select,date_divide classSaleOrderFilter(django_filters.FilterSet): defselect_code(queryset,name,value): print(name) returncode_select(value) defselect_date(queryset,name,value): create_time=date_divide(value) date_start=create_time['start_time'] date_end=create_time['end_time'] #在已经查出来的其他参数的基础上增加查询条件 returnqueryset.filter(create_time__gt=date_start,create_time__lt=date_end) classMeta: model=SaleOrder fields={'status':['exact'], 'code':[], 'create_time':[], } create_time=django_filters.CharFilter(method='select_date', widget=forms.TextInput(attrs={'class':'form-controldaterange-time', 'name':'date', })) status=django_filters.ChoiceFilter(choices=STATUS_ENUM, widget=forms.Select(attrs={'class':'select', 'name':'status', 'data-width':'100%'})) code=django_filters.CharFilter(method='select_code',name='code', widget=forms.TextInput(attrs={'name':'platform_order_code', 'class':'form-control', 'placeholder':'订单号'}))
对应前端的结果集
{%csrf_token%} {%forfooinfilter.qs%}{%endfor%} {{foo.platform_order_code}} {{foo.code}}
django-filter对应的前端的form:
{{filter.form.as_p}}
以上这篇django-filter和普通查询的例子就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。