django filters實現(xiàn)數(shù)據(jù)過濾的示例代碼
當(dāng)前循環(huán). 作用 default 數(shù)據(jù)為空時設(shè)置默認(rèn)值 length 取變量長度 filesizeformat 文件大小轉(zhuǎn)成可讀 slice 從指定位置到指定位切片 date datetime取到的時間,轉(zhuǎn)成指定格式 safe 防止XSS攻擊、加上safe才能傳標(biāo)簽 truncatechars 取摘顯示一段剩下的…
例子
{#格式 值|函數(shù)#}{# 如果沒有值,那么使用默認(rèn)值#} <p>{{ bucunzai|default:’空的哦’ }}</p>{# 取出變量長度#} <q>{{ name }}--{{ name|length }}</q>{# 文件大小轉(zhuǎn)換成可讀型 kb 自動轉(zhuǎn)成bm、g、tb#} <p>文件大小{{ file_size|filesizeformat }}</p>{# 切片 從指定位置到指定位 ,例:第3位到-2位#} <p>切片:{{ slice_str|slice:’3:-2’ }}</p>{# 把datetime取到的時間,轉(zhuǎn)成指定格式#} <p>格式化:{{ now|date:’Y-m-d H:i:s’ }}</p>{# 如果后端內(nèi)容包含標(biāo)簽,那么加上safe 才能轉(zhuǎn)義(防止用戶直接加script標(biāo)簽作弊)防XSS攻擊#} <p>{{ h_html|safe }}</p>{# 取摘要只顯示一段,指定取長度后面...例:120個字符 #} <p>長文本:{{ p_str|truncatechars:12 }}</p>
1、視圖
class UserView(ListAPIView): '''用戶列表''' queryset = User.objects.all() serializer_class = UserSerializer filter_backends = (DjangoFilterBackend,) filter_class = UserMonthFilter # 指定過濾類
2、過濾類
class RobotFilter(django_filters.FilterSet): # 使用過濾:URL?created_start_time=2020_01-20&created_end_time=2020_01-21 robot_id = django_filters.CharFilter(field_name=’id’) machine_id = django_filters.CharFilter(field_name=’machine_id’) city = django_filters.CharFilter(field_name=’city’) # lookup_expr(可選)為判斷條件,field_name(必選)為模型類屬性,created_time查詢字符串 created_time= django_filters.CharFilter(field_name=’created_at’, lookup_expr=’startswith’) created_start_time = django_filters.DateTimeFilter(field_name=’created_at’, lookup_expr=’gt’) created_end_time = django_filters.DateTimeFilter(field_name=’created_at’, lookup_expr=’lt’) problem_isnull = django_filters.BooleanFilter(field_name=’problem’, lookup_expr=’isnull’) name = django_filters.CharFilter(lookup_expr=’iexact’) # iexact表示精確匹配, 并且忽略大小寫 author = django_filters.CharFilter(lookup_expr=’icontains’) #icontains表示模糊查詢(包含),并且忽略大小寫 price = django_filters.NumberFilter(look_expr=’exact’) #exact表示精確匹配 task_res_state = django_filters.CharFilter(method='get_task_res_state')def get_task_res_state(self, queryset, *arg):if str(arg[1]) == '0': # arg[1]=(’task_res_state’, ’0’) task_res = (1, 2, 3)else: task_res = (0, 4, 5, 6)print(task_res)queryset = queryset.filter(task_res__in=task_res)return queryset class Meta:model = Robotfields = [’robot_id’, ’machine_id’, 'city', 'created_start_time', 'created_end_time', ’created_time’, ’firmware_version’, ’state’, 'robot_type', 'hardware_version', 'exist_map', ’task_res_state’]
到此這篇關(guān)于django filters實現(xiàn)數(shù)據(jù)過濾的示例代碼的文章就介紹到這了,更多相關(guān)django filters 數(shù)據(jù)過濾 內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. Android 實現(xiàn)徹底退出自己APP 并殺掉所有相關(guān)的進(jìn)程2. Vue實現(xiàn)仿iPhone懸浮球的示例代碼3. vue使用moment如何將時間戳轉(zhuǎn)為標(biāo)準(zhǔn)日期時間格式4. 一個 2 年 Android 開發(fā)者的 18 條忠告5. js select支持手動輸入功能實現(xiàn)代碼6. Spring的異常重試框架Spring Retry簡單配置操作7. Android studio 解決logcat無過濾工具欄的操作8. 什么是Python變量作用域9. PHP正則表達(dá)式函數(shù)preg_replace用法實例分析10. vue-drag-chart 拖動/縮放圖表組件的實例代碼
