您好,登錄后才能下訂單哦!
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_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'] # 在已經查出來的其他參數的基礎上增加查詢條件 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和普通查詢的例子就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。