django开发中django-filter的用法

2022年3月25日 12:02 by wst

django

web开发中根据前端传的参数过滤数据是很常见的。

在Django中,插件(django-filter)对这个功能进行了加强。

下面列出常见用法:

前提

1. 安装插件:

pip install django-filter

2. 添加配置(settings.py)

INSTALLED_APPS = [
    ...
    'django_filters',
]

REST_FRAMEWORK = {
   # 过滤器默认后端
    'DEFAULT_FILTER_BACKENDS': (
           'django_filters.rest_framework.DjangoFilterBackend',),
}

3. 定义模型(models.py)

from django.db import models

# Create your models here.

class BookInfo(models.Model):
    btitle = models.CharField(max_length=20, verbose_name="名称")
    bpub_date = models.DateField(verbose_name="发布日期")
    bread = models.IntegerField(default=0, verbose_name="阅读量")
    bcomment = models.IntegerField(default=0, verbose_name="评论量")
    is_delete = models.BooleanField(default=False, verbose_name="逻辑删除")

4. 定义序列化类(serializer.py)

from rest_framework import serializers

class BookInfoSerializer(serializers.Serializer):
    # read_only = True 只读, label:字段说明信息
    id = serializers.IntegerField(read_only=True, label="书籍编号")
    btitle = serializers.CharField(max_length=20, min_length=3, label="名称")
    bpub_date = serializers.DateField(label="发布日期")
    bread = serializers.IntegerField(default=0, min_value=0, label="阅读量")
    bcomment = serializers.IntegerField(default=0, max_value=50, label="评论量")
    is_delete = serializers.BooleanField(default=False, label="逻辑删除")

5. 定义视图(views.py)

定义视图之前,假定过滤器(filters.py)已经存在(细节下面讲)。

from rest_framework.generics import ListAPIView

from .models import BookInfo
from .serializer import BookInfoSerializer
from .filters import BookFilter


class BookView(ListAPIView):
    """ 图书查询"""
    queryset = BookInfo.objects.all()
    serializer_class = BookInfoSerializer
    filter_class = BookFilter

常见用法

1. 对字符串类型过滤、数值类型大小限制

from django_filters import rest_framework as filters

from .models import BookInfo


class BookFilter(filters.FilterSet):
    min_read = filters.NumberFilter(field_name='bread', lookup_expr='gte')
    max_read = filters.NumberFilter(field_name='bread', lookup_expr='lte')

    class Meta:
        model = BookInfo
        fields = {
            'btitle': ['icontains'],
            'bcomment': ['gte', 'lte']
        }

说明:

* 对bread字段进行限制,前端需要传递参数min_read(最小值), max_read(最大值);

* 对btitle字段进行限制,前端需要传递参数btitle__icontains(包含字符)

* 对bcomment进行限制,前端需要传递参数bcomment__gte(最小值),bcomment__lte(最大值)

* Meta中的fields变量一定要写,不写会报错,哪怕是个空数组:fields=[] 表示只对bread进行过滤,前端可以传两个参数min_read, max_read;

2. 默认进行精确查找

from django_filters import rest_framework as filters

from .models import BookInfo


class BookFilter(filters.FilterSet):

    class Meta:
        model = BookInfo
        fields = [
            'bpub_date', 'is_delete'
        ]

 说明:

1. 对bpub_date精确查找,前端可传参数bpub_date;

2. 对is_delete精确查找,前端可传参数is_delete;

 

总结

1. 最对某个模型的过滤,需要在Meta中体现,fields变量也要有;

2. fields变量必须有,可以为列表或者字典;

3. fields为列表,则需要包含被过滤的字段;

4. fields为字典,则key为需要过滤的字段,value为过滤方式;


Comments(126) Add Your Comment

Dohsks
buy generic lipitor 40mg <a href="https://lipiws.top/">purchase lipitor pills</a> buy atorvastatin 80mg generic
Qdeyem
order cipro 1000mg generic - <a href="https://cipropro.top/bactrimos/">buy bactrim 480mg generic</a> augmentin 1000mg tablet
Bekrty
buy baycip online cheap - <a href="https://metroagyl.top/">baycip over the counter</a> buy augmentin 1000mg
Pdicfd
order ciprofloxacin without prescription - <a href="https://septrim.top/trimox/">order amoxicillin pill</a> buy erythromycin 500mg sale
Mpmgsv
brand metronidazole 400mg - <a href="https://metroagyl.top/azithromycin/">buy azithromycin pills for sale</a> zithromax 500mg over the counter
Setzwv
ivermectin 12mg tablets - <a href="https://keflexin.top/cefixime/">suprax over the counter</a> brand sumycin
Odxojb
valacyclovir generic - <a href="https://gnantiviralp.com/starlix/">order nateglinide 120 mg generic</a> buy acyclovir 400mg online cheap
Yrrsnf
buy ampicillin online cheap <a href="https://ampiacil.top/amoxil500/">order amoxicillin pill</a> buy amoxicillin generic
Ecilfd
order metronidazole for sale - <a href="https://metroagyl.top/keflexcapsule/">cheap amoxicillin without prescription</a> azithromycin 250mg cost
Heywmx
buy furosemide online cheap - <a href="https://antipathogenc.com/atacand/">buy atacand sale</a> oral captopril 25 mg
Ukocij
cost metformin - <a href="https://gnantiacidity.com/lincocin/">order lincocin 500mg generic</a> cost lincomycin
Hsbgtm
buy retrovir 300 mg for sale - <a href="https://canadiangnp.com/avapro/">purchase irbesartan without prescription</a> buy zyloprim without a prescription
Auaugq
oral clozapine 50mg - <a href="https://genonlinep.com/amaryl/">buy generic glimepiride</a> buy famotidine
Fgyduo
quetiapine for sale - <a href="https://gnkantdepres.com/luvox/">cost luvox 100mg</a> buy cheap generic eskalith
Zvzaic
order anafranil generic - <a href="https://antdeponline.com/celexa/">buy celexa 40mg pill</a> sinequan 25mg price
Etpruf
order hydroxyzine without prescription - <a href="https://antdepls.com/buspar/">buspirone 5mg cheap</a> oral endep
Sqbrsi
order amoxiclav sale - <a href="https://atbioinfo.com/">buy amoxiclav for sale</a> cipro 500mg generic
Thbhzw
order amoxicillin for sale - <a href="https://atbioxotc.com/ceftin/">buy cefuroxime online cheap</a> cipro cheap
Xfdjie
buy generic azithromycin for sale - <a href="https://gncatbp.com/ctinidazole/">buy tindamax pills for sale</a> buy ciplox 500 mg sale
Ffcjra
order cleocin for sale - <a href="https://cadbiot.com/chloramphenicol/">order chloromycetin generic</a> chloramphenicol online order
Oqvhpp
buy stromectol 2mg - <a href="https://antibpl.com/szdoryx/">buy doxycycline medication</a> order generic cefaclor 250mg
Apmecm
order ventolin 4mg online - <a href="https://antxallergic.com/dftheo-24/">buy theo-24 Cr 400mg sale</a> theo-24 Cr 400 mg drug
Osnioh
buy medrol pill - <a href="https://ntallegpl.com/montelukast/">singulair online order</a> buy astelin 10 ml online cheap
Urgepp
clarinex uk - <a href="https://rxtallerg.com/flixotidespray/">flixotide oral</a> ventolin 2mg usa
Cjxila
buy metformin for sale - <a href="https://arxdepress.com/sitagliptin50/">buy januvia without a prescription</a> purchase acarbose sale
Eoywvg
glyburide canada - <a href="https://prodeprpl.com/pioglitazone30/">actos 15mg brand</a> order dapagliflozin 10 mg for sale
Mfwvxr
buy generic prandin 1mg - <a href="https://depressinfo.com/">prandin 1mg brand</a> buy jardiance 10mg generic
Bwqvjs
rybelsus without prescription - <a href="https://infodeppl.com/">rybelsus drug</a> desmopressin over the counter
Bczqxd
order terbinafine sale - <a href="https://treatfungusx.com/xgrifulvinvs/">buy cheap generic grifulvin v</a> purchase griseofulvin
Sitybd
buy nizoral for sale - <a href="https://antifungusrp.com/">order nizoral online cheap</a> purchase itraconazole
Fngwol
famciclovir over the counter - <a href="https://amvinherpes.com/gnvalaciclovir/">buy valcivir paypal</a> buy cheap valaciclovir
Avgplh
order digoxin 250 mg - <a href="https://blpressureok.com/isoptinpillmg/">buy calan no prescription</a> buy lasix for sale diuretic
Eweexh
order lopressor 50mg online cheap - <a href="https://bloodpresspl.com/olmesartan/">olmesartan order</a> adalat cost
Sbhois
hydrochlorothiazide 25mg tablet - <a href="https://norvapril.com/felodipine/">brand felodipine 5mg</a> cost zebeta
Yqgask
nitroglycerin price - <a href="https://nitroproxl.com/">order nitroglycerin online cheap</a> buy diovan online cheap
Cqpywn
simvastatin acquaint - <a href="https://canescholest.com/gemfibrozil/">lopid bell</a> lipitor relative
Qipxvh
rosuvastatin often - <a href="https://antcholesterol.com/pravastatin/">pravastatin galaxy</a> caduet online crowd
Xsvztu
buy viagra professional burst - <a href="https://edsildps.com/malegra/">malegra valentine</a> levitra oral jelly year
Oswcrl
priligy excitement - <a href="https://promedprili.com/aurogra/">aurogra petunia</a> cialis with dapoxetine stretch
Qwolhp
cenforce online balloon - <a href="https://xcenforcem.com/">cenforce alice</a> brand viagra pills wave
Uooskm
brand cialis flat - <a href="https://probrandtad.com/viagrasofttabs/">viagra soft tabs department</a> penisole fad
Ctllhd
brand cialis settle - <a href="https://probrandtad.com/apcalissx/">apcalis straight</a> penisole rag
Laxfgd
cialis soft tabs hang - <a href="https://supervalip.com/tadarisepills/">tadarise set</a> viagra oral jelly online frown
Kqltzb
cialis soft tabs online local - <a href="https://supervalip.com/cialisoraljelly/">cialis oral jelly survey</a> viagra oral jelly online arrival
Nkafjg
dapoxetine figure - <a href="https://promedprili.com/zudena/">zudena assemble</a> cialis with dapoxetine trouble
Sugriq
cenforce often - <a href="https://xcenforcem.com/levitraprofessional/">levitra professional online devil</a> brand viagra draw
Jzohoq
asthma treatment office - <a href="https://bsasthmaps.com/">inhalers for asthma strong</a> inhalers for asthma give
Yuevla
acne medication discover - <a href="https://placnemedx.com/">acne treatment vague</a> acne treatment invent
Qthjno
prostatitis medications present - <a href="https://xprosttreat.com/">prostatitis medications distract</a> pills for treat prostatitis alice
Ebhotz
uti antibiotics decay - <a href="https://amenahealthp.com/">treatment for uti extraordinary</a> uti treatment bay
Buhudp
claritin pills below - <a href="https://clatadine.top/">claritin pills tale</a> claritin legend
Wxythu
valacyclovir marvellous - <a href="https://gnantiviralp.com/">valacyclovir rip</a> valacyclovir western
Cymxaq
dapoxetine dream - <a href="https://prilixgn.top/">priligy thou</a> priligy physician
Jqvmhd
claritin menace - <a href="https://clatadine.top/">claritin pills blush</a> loratadine medication moral
Ymgrld
ascorbic acid wolf - <a href="https://ascxacid.com/">ascorbic acid key</a> ascorbic acid relative
Tcskmh
promethazine shame - <a href="https://prohnrg.com/">promethazine bet</a> promethazine drive
Dnaxoi
biaxin happiness - <a href="https://gastropls.com/albendazole400/">albenza eastern</a> cytotec pills wealth
Rpywdr
fludrocortisone apparent - <a href="https://gastroplusp.com/omepprilosec/">prilosec pills hint</a> prevacid haste
Kefbvx
generic aciphex - <a href="https://gastrointesl.com/metoclopramide/">metoclopramide 20mg uk</a> motilium 10mg sale
Yvkolt
buy dulcolax 5mg generic - <a href="https://gastroinfop.com/">buy dulcolax pills</a> order liv52 20mg without prescription
Wpoupy
buy zovirax cream - <a href="https://danaterone.shop/">hydroquinone canada</a> buy duphaston without a prescription
Cvacqn
buy bactrim 480mg pill - <a href="https://tobmycin.com/">tobramycin 10mg uk</a> order tobrex 10mg generic
Qdymsx
griseofulvin over the counter - <a href="https://dipyrilx.com/">dipyridamole 100mg usa</a> buy lopid 300mg
Hwtdzf
dapagliflozin 10 mg ca - <a href="https://precarbos.com/">precose drug</a> order precose 50mg online
Hddykr
dramamine 50 mg sale - <a href="https://bisacolax.com/">order dimenhydrinate 50mg</a> order actonel 35 mg generic
Atiqdo
order enalapril 10mg - <a href="https://xalanoprost.com/">order latanoprost online cheap</a> latanoprost order online
Gurxqm
generic monograph - <a href="https://cilosetal.com/">order pletal</a> purchase pletal without prescription
Awynbx
piroxicam 20mg ca - <a href="https://feldexicam.com/">piroxicam tablet</a> rivastigmine 3mg cheap
Njeptv
purchase piracetam for sale - <a href="https://nootquin.com/levofloxacin/">levofloxacin us</a> order sinemet online cheap
Uhxkhf
buy hydroxyurea medication - <a href="https://hydroydrinfo.com/">buy hydroxyurea paypal</a> methocarbamol for sale
Mpqmbd
divalproex pills - <a href="https://adepamox.com/topiramate/">order topamax online cheap</a> topiramate oral
Ryuxki
norpace brand - <a href="https://anorpica.com/pregabal/">pregabalin over the counter</a> order thorazine 50 mg pills
Rduecv
generic aldactone 25mg - <a href="https://aldantinep.com/dipyridamole/">order dipyridamole online</a> naltrexone 50 mg tablet
Yplokz
buy generic cytoxan - <a href="https://cycloxalp.com/antivert/">order generic meclizine 25 mg</a> buy trimetazidine no prescription
Ybbbwh
cyclobenzaprine brand - <a href="https://abflequine.com/donepezil/">order donepezil sale</a> order enalapril online cheap
Lbmyik
buy zofran cheap - <a href="https://azofarininfo.com/procyclidine/">procyclidine pill</a> buy cheap generic requip
Svijid
ascorbic acid 500 mg usa - <a href="https://mdacidinfo.com/bromhexine/">bromhexine usa</a> prochlorperazine pills
Szfdyv
order durex gel sale - <a href="https://xalaplinfo.com/durexcondoms/">purchase durex condoms cheap</a> xalatan order
Jcyhbp
order minoxidil sale - <a href="https://hairlossmedinfo.com/finasteridehl/">buy finasteride pills for sale</a> order finasteride generic
Sxkqjm
order generic arava 10mg - <a href="https://infohealthybones.com/calciumcarbonate/">calcium carbonate over the counter</a> buy cartidin medication
Mbgwmu
purchase verapamil generic - <a href="https://infoheartdisea.com/valsartan/">purchase valsartan sale</a> brand tenoretic
Nliazz
tenormin pill - <a href="https://heartmedinfox.com/carvedilol/">purchase carvedilol without prescription</a> coreg order online
Tymiry
atorvastatin tablet - <a href="https://infoxheartmed.com/">purchase atorlip for sale</a> buy generic bystolic
Unpigg
gasex oral - <a href="https://herbalinfomez.com/diabecon/">diabecon sale</a> order diabecon pill
Aetwns
lasuna price - <a href="https://infoherbalmz.com/diarex/">cheap diarex</a> buy himcolin
Ccheui
purchase noroxin sale - <a href="https://gmenshth.com/flutamide/">flutamide online</a> confido cost
Zuehgb
order speman generic - <a href="https://spmensht.com/">buy speman pill</a> fincar over the counter
Qqoymp
cheap finasteride generic - <a href="https://finmenura.com/">finax oral</a> cheap uroxatral
Ikdpqw
order hytrin sale - <a href="https://hymenmax.com/tamsulosin/">tamsulosin 0.4mg us</a> priligy order
Ojuaqa
order trileptal pills - <a href="https://trileoxine.com/">trileptal 300mg pills</a> cheap synthroid generic
Elskyg
order imusporin online cheap - <a href="https://asimusxate.com/methotrexate/">methotrexate for sale online</a> gloperba drug
Eozdzc
lactulose online order - <a href="https://duphalinfo.com/">buy lactulose generic</a> buy betahistine 16 mg
Kijwsd
buy calcort pills for sale - <a href="https://lazacort.com/brimonidine/">brimonidine online buy</a> cost alphagan
Atfrkx
buy neurontin 800mg without prescription - <a href="https://aneutrin.com/sulfasalazine/">order azulfidine 500mg generic</a> order azulfidine pill
Cnmrmb
buy generic besivance - <a href="https://besifxcist.com/carbocysteine/">order carbocisteine pills</a> buy cheap sildamax
Wtdlse
buy probenecid without a prescription - <a href="https://bendoltol.com/">order benemid 500 mg online cheap</a> order carbamazepine 400mg for sale
Deggmx
celebrex 200mg for sale - <a href="https://celespas.com/flavoxate/">urispas where to buy</a> generic indocin
Yfaglv
voltaren ca - <a href="https://dicloltarin.com/">buy generic diclofenac 50mg</a> aspirin price
Pzmuys
generic mestinon 60mg - <a href="https://mestonsx.com/asumatriptan/">order sumatriptan 25mg online</a> buy imuran sale
Pbmlvg
rumalaya drug - <a href="https://rumaxtol.com/amitriptyline/">elavil pill</a> buy amitriptyline online cheap
Xghjcp
order diclofenac without prescription - <a href="https://vovetosa.com/animodipine/">purchase nimotop</a> purchase nimodipine generic
Eaynmz
buy cyproheptadine for sale - <a href="https://periheptadn.com/aszanaflex/">zanaflex generic</a> order tizanidine 2mg without prescription
Esfscn
order mobic pill - <a href="https://meloxiptan.com/">mobic 15mg tablet</a> buy toradol
Cvxmqn
cefdinir 300 mg canada - <a href="https://omnixcin.com/clindamycin/">buy generic clindamycin online</a> buy cheap generic clindamycin
Tyuqal
purchase trihexyphenidyl generic - <a href="https://voltapll.com/diclofenacgel/">diclofenac gel where to purchase</a> diclofenac gel order online
Zjhvqc
buy prednisone 20mg generic - <a href="https://apreplson.com/prednisolone/">prednisolone 40mg usa</a> order zovirax without prescription
Cmmbis
accutane 20mg pill - <a href="https://aisotane.com/asdeltasone/">deltasone 10mg canada</a> generic deltasone 40mg
Exdrxc
buy betamethasone 20gm online cheap - <a href="https://betnoson.com/">buy betamethasone 20 gm online</a> monobenzone cost
Minnut
order permethrin cream - <a href="https://actizacs.com/asbenzac/">buy cheap benzoyl peroxide</a> oral tretinoin cream
Pilzow
order flagyl generic - <a href="https://ametronles.com/">purchase metronidazole sale</a> buy cenforce 50mg online
Tfqbyx
buy generic augmentin - <a href="https://alevonted.com/">synthroid 150mcg pills</a> buy synthroid 75mcg pill
Xdombl
cozaar 25mg for sale - <a href="https://cozartan.com/">buy losartan 25mg pills</a> keflex 250mg generic
Illnmp
clindamycin pills - <a href="https://indometnp.com/">order generic indomethacin</a> buy indomethacin without prescription
Ktzocv
modafinil 200mg cheap - <a href="https://sleepagil.com/melatonin/">meloset 3mg tablet</a> pill meloset
Srfost
buy generic crotamiton - <a href="https://aeuracream.com/caczone/">buy aczone pills</a> order aczone without prescription
Vpjmnv
order zyban pill - <a href="https://bupropsl.com/ayurslim/">buy ayurslim generic</a> buy cheap shuddha guggulu
Mwitlu
xeloda 500mg ca - <a href="https://xelocap.com/naproxen/">buy naproxen cheap</a> danazol 100mg cheap
Udbqlt
buy progesterone 200mg without prescription - <a href="https://apromid.com/">prometrium cost</a> cheap clomiphene without prescription
Rmgkqv
order alendronate online - <a href="https://pilaxmax.com/medroxyprogesterone/">order medroxyprogesterone 5mg without prescription</a> medroxyprogesterone order online
Lxonpq
order aygestin 5 mg online - <a href="https://norethgep.com/bimatoprost/">generic careprost</a> order yasmin pill
Emzuwm
buy generic yasmin - <a href="https://festrolp.com/">yasmin brand</a> order anastrozole 1mg without prescription
Uigwok
buy cabergoline 0.5mg online - <a href="https://adostilin.com/">buy dostinex medication</a> buy alesse for sale
Gotmgd
гѓ—гѓ¬гѓ‰гѓ‹гѓі и–¬е±ЂгЃ§иІ·гЃ€г‚‹ - <a href="https://jpaonlinep.com/jamoxicillin/">г‚ўгѓўг‚­г‚·г‚·гѓЄгѓі и–¬е±ЂгЃ§иІ·гЃ€г‚‹</a> г‚ёг‚№гѓ­гѓћгѓѓг‚Ї гЃ®иіје…Ґ
Uzxdwg
バイアグラ おすすめ - <a href="https://jpedpharm.com/">シルデナフィル 副作用</a> シアリス 海外通販
Nuulrm
プレドニン の購入 - <a href="https://jpanfarap.com/">プレドニン は通販での購</a> イソトレチノイン 個人輸入 おすすめ
Bjvvtu
eriacta court - <a href="https://eriagra.com/fforzestf/">forzest jump</a> forzest bleed