django-filter和普通查询的例子

时间:2021-05-22

pythong在使用中,尤其是django的查询过程中插件还是不少的,最近发现了一个插件django-filter ,还挺好用的

1.最原始直接根据条件查询

def search(request): request.encoding = 'utf-8' if 'platform_order_code' in request.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, }) return response

2、djamgo-filter插件查询,根据filter中的查询条件自动生成查询的额对话框,文本框,下拉框等;

(https://django-filter.readthedocs.io/en/master/guide/install.html)

def query_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] return render(request, 'ofc/list.html', {'filter': filter, "menus": menus})

对应的filter.py的处理

widget可以给对应的生成的空间添加class等样式

import django_filtersfrom django import formsfrom django.db.models import Qfrom ofc.enum import STATUS_ENUMfrom ofc.models import SaleOrderfrom ofc.utils import code_select, date_divideclass SaleOrderFilter(django_filters.FilterSet): def select_code(queryset, name, value): print(name) return code_select(value) def select_date(queryset, name, value): create_time = date_divide(value) date_start = create_time['start_time'] date_end = create_time['end_time'] # 在已经查出来的其他参数的基础上增加查询条件 return queryset.filter(create_time__gt=date_start, create_time__lt=date_end) class Meta: model = SaleOrder fields = {'status': ['exact'], 'code': [], 'create_time': [], } create_time = django_filters.CharFilter(method='select_date', widget=forms.TextInput(attrs={'class': 'form-control daterange-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 %}{% for foo in filter.qs %} <tr> <td>{{ foo.platform_order_code }}</td> <td>{{ foo.code }}</td> </tr>{% endfor %}

django-filter对应的前端的form:

{{ filter.form.as_p }}

以上这篇django-filter和普通查询的例子就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章