问题描述
我是一个初学者,并且使用Django rest框架开发了一个REST API项目.PostgreSQL数据库中有一堆带有文本字段的记录,我有一些关键字列表.我正在尝试过滤包含此文本字段中一个或某些关键字列表中的单词的数据.
您能否建议我另一种方法来组织DRF中的过滤,方法是一次使用整个关键字列表,而无需以表格形式输入它们?
我正在尝试使用django_filters
如果是过滤器类:
#过滤器类DataFilter(django_filters.rest_framework.FilterSet):关键字= CharFilter(field_name ='description',lookup_expr ='icontains')类Meta:型号=数据字段=('关键字',)
如果是视图类:
#视图类DataList(generics.ListAPIView):def get_queryset(self):返回Data.objects.filter(deadline__gte = date.today())serializer_class = DataSerializerfilter_backends =(filters.DjangoFilterBackend,)filterset_class =数据过滤器
但是在这种情况下,它仅按我在表单中输入的一个单词过滤.
我认为您可以这样做:
首先,从
I'm a beginner and develop a little REST API project with Django rest framework. There are a bunch of records in PostgreSQL database with a text field and I have some lists of keywords. I'm trying to filter data which contain words from one or some my lists of keywords in this text field.
Can you advise me another way around to organize filtering in DRF by using a whole list of keywords at once without entering them in a form?
I'm trying to do it with django_filters
Here if filter class:
# filter
class DataFilter(django_filters.rest_framework.FilterSet):
keyword = CharFilter(field_name='description', lookup_expr='icontains')
class Meta:
model = Data
fields = ('keyword', )
Here if view class:
# view
class DataList(generics.ListAPIView):
def get_queryset(self):
return Data.objects.filter(deadline__gte=date.today())
serializer_class = DataSerializer
filter_backends = (filters.DjangoFilterBackend,)
filterset_class = DataFilter
But in this case, it filters only by one word which I enter in the form.
I think you can do it like this:
First, create a new filter set subclassing from BaseInFilter and CharFilter
:
class CharInFilter(django_filters.BaseInFilter, django_filters.CharFilter):
pass
Then, update your FilterSet class like this:
class DataFilter(django_filters.FilterSet):
keyword__in = CharInFilter(field_name='keyword', lookup_expr='in')
class Meta:
model = Data
fields = []
Then you can use this FilterSet(same as your current implementation) like this:
class DataList(generics.ListAPIView):
def get_queryset(self):
return Data.objects.filter(deadline__gte=date.today())
serializer_class = DataSerializer
filter_backends = (filters.DjangoFilterBackend,)
filterset_class = DataFilter
While using this filterset in DRF template, you need to input your values in comma separated format, like this:
这篇关于如何通过多个关键字从数据库中过滤DRF中的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!