您好,登錄后才能下訂單哦!
pythong在使用中,尤其是django的查詢過程中插件還是不少的,最近發(fā)現(xiàn)了一個插件django-filter ,還挺好用的
1.最原始直接根據(jù)條件查詢
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插件查詢,根據(jù)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') # 如果有參數(shù),則從所有訂單中篩選 if(my_param): filter = SaleOrderFilter(request.GET, queryset=SaleOrder.objects.all()) # 如果沒有參數(shù)的,則默認(rèn)查詢今天的 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})
對應(yīng)的filter.py的處理
widget可以給對應(yīng)的生成的空間添加class等樣式
import django_filters from django import forms from django.db.models import Q from ofc.enum import STATUS_ENUM from ofc.models import SaleOrder from ofc.utils import code_select, date_divide class 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'] # 在已經(jīng)查出來的其他參數(shù)的基礎(chǔ)上增加查詢條件 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': '訂單號'}))
對應(yīng)前端的結(jié)果集
{% csrf_token %} {% for foo in filter.qs %} <tr> <td>{{ foo.platform_order_code }}</td> <td>{{ foo.code }}</td> </tr> {% endfor %}
django-filter對應(yīng)的前端的form:
{{ filter.form.as_p }}
以上這篇django-filter和普通查詢的例子就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持億速云。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。