我想在Django Restframework中发出API请求,例如 http://localhost:8000/apis/services/?page=1&name=2
模型
from django.contrib.postgres.fields import JSONField
class Service(models.Model):
name = JSONField(default=dict)
APIView
class DashboardServicesAPIView(ListAPIView):
queryset = Service.objects.none()
serializer_class = ServiceSerializer
permission_classes = (AllowAny,)
filter_class = ServiceFilter
def get_queryset(self):
return Service.objects.filter(vendor__company=self.request.user.userprofile.company)
过滤器集
class ServiceFilter(django_filters.rest_framework.FilterSet):
name = django_filters.CharFilter(field_name="name",
lookup_expr='icontains')
class Meta:
model = Service
fields = [ "name"]
过滤settings.py中的后端
REST_FRAMEWORK = {
'DEFAULT_FILTER_BACKENDS': (
'django_filters.rest_framework.DjangoFilterBackend',
),
.
.
.
使用过滤器querystring的查询不起作用,总是返回相同的结果。 我错过了处理JSON的任何帮助吗?
答案 0 :(得分:1)
您需要添加filter_backends
才能将django_filter
与drf
集成
class DashboardServicesAPIView(ListAPIView):
queryset = Service.objects.none()
serializer_class = ServiceSerializer
permission_classes = (AllowAny,)
filter_class = ServiceFilter
filter_backends = (filters.DjangoFilterBackend,)
def get_queryset(self):
return Service.objects.filter(vendor__company=self.request.user.userprofile.company)
https://django-filter.readthedocs.io/en/master/guide/rest_framework.html
django-filter库包含DjangoFilterBackend类,该类支持针对REST框架的高度可自定义的字段过滤。