Django过滤器后端 [英] Django Filter Backend
本文介绍了Django过滤器后端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用Django rest framework API,我正在尝试通过first_name或last_name或两者都进行过滤。
这是我的 ContactViewSet.py :
I'm working with Django rest framework API, I am trying to make a filter by first_name or by last_name or by both of them. This is my ContactViewSet.py :
class ContactViewSet(viewsets.ModelViewSet):
queryset = Contact.objects.all()
serializer_class = ContactSerializer
filter_backends = (DjangoFilterBackend, )
filter_fields = ('first_name', 'last_name')
lookup_field = 'idContact'
我的DRF设置:
REST_FRAMEWORK = {
'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',),
}
我的actuel请求网址如下:
My actuel request url looks like :
http://localhost:8000/api/v1/contacts/?first_name=Clair&last_name=Test
但是我正在寻找这样的东西:
But I'm looking for something like this :
http://localhost:8000/api/v1/contacts/?first_name=Cl**&last_name=Tes**
任何帮助将不胜感激..
Any help would be appreciated ..
推荐答案
我通过修改类ContactFilter来解决我的问题,
I solved my problem by modifying my class ContactFilter like this:
import django_filters
from .models import Contact
class ContactFilter(django_filters.FilterSet):
class Meta:
model = Contact
fields = {
'first_name': ['startswith'],
'last_name': ['startswith'],
}
together = ['first_name', 'last_name']
在我看来,我只需要这样做:
And in my view I just had to do this :
class ContactViewSet(viewsets.ModelViewSet):
queryset = Contact.objects.all()
serializer_class = ContactSerializer
filter_class = ContactFilter
我的请求网址如下所示:
My request url looks like :
http://localhost:8000/api/v1/contact/?first_name__contains=Cl&last_name__contains=Tes
但是我仍然想知道我是否可以有这样的东西在Django中
But I still wonder if I can have something like this in Django
http://localhost:8000/api/v1/contacts/?first_name=Cl**&last_name=Tes**
这篇关于Django过滤器后端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文