如何允许'filter'查询参数Django REST框架JSON API?

laawzig2  于 2023-02-10  发布在  Go
关注(0)|答案(1)|浏览(160)

我正在使用Django REST框架和djangorestframework-jsonapi
当我使用filter[name]=THEOS DRF查询时,在浏览器中出现错误。我尝试使用此URL查询

http://localhost:8000/api/space_objects/?filter[name]=THEOS

JSON API中的其他参数我可以使用它,没有任何问题。

ValidationError at /api/space_objects/
[ErrorDetail(string='invalid filter[name]', code='invalid')]

这是我的DRF JSON API设置DRF JSON API Documentation

REST_FRAMEWORK = {
    'PAGE_SIZE': 10,
    'EXCEPTION_HANDLER': 'rest_framework_json_api.exceptions.exception_handler',
    'DEFAULT_PAGINATION_CLASS':
        'rest_framework_json_api.pagination.JsonApiPageNumberPagination',
    'DEFAULT_PARSER_CLASSES': (
        'rest_framework_json_api.parsers.JSONParser',
        'rest_framework.parsers.FormParser',
        'rest_framework.parsers.MultiPartParser'
    ),
    'DEFAULT_RENDERER_CLASSES': (
        'rest_framework_json_api.renderers.JSONRenderer',
        # If you're performance testing, you will want to use the browseable API
        # without forms, as the forms can generate their own queries.
        # If performance testing, enable:
        # 'example.utils.BrowsableAPIRendererWithoutForms',
        # Otherwise, to play around with the browseable API, enable:
        'rest_framework_json_api.renderers.BrowsableAPIRenderer'
    ),
    'DEFAULT_METADATA_CLASS': 'rest_framework_json_api.metadata.JSONAPIMetadata',
    'DEFAULT_SCHEMA_CLASS': 'rest_framework_json_api.schemas.openapi.AutoSchema',
    'DEFAULT_FILTER_BACKENDS': (
        'rest_framework_json_api.filters.QueryParameterValidationFilter',
        'rest_framework_json_api.filters.OrderingFilter',
        'rest_framework_json_api.django_filters.DjangoFilterBackend',
        'rest_framework.filters.SearchFilter',
    ),
    'SEARCH_PARAM': 'filter[search]',
    'TEST_REQUEST_RENDERER_CLASSES': (
        'rest_framework_json_api.renderers.JSONRenderer',
    ),
    'TEST_REQUEST_DEFAULT_FORMAT': 'vnd.api+json'
}

我的模特

class SpaceObject(models.Model):
  class Meta:
    ordering = ['norad']

  norad = models.IntegerField(primary_key=True)
  object_type = models.CharField(max_length=200, null=True)
  name = models.CharField(max_length=200, null=True)
  period = models.FloatField(null=True)
  inclination = models.FloatField(null=True)
  apogee = models.FloatField(null=True)
  perigee = models.FloatField(null=True)
  rcs_size = models.CharField(max_length=200, null=True)
  tle_1 = models.CharField(max_length=200, null=True)
  tle_2 = models.CharField(max_length=200, null=True)
  last_updated = models.DateTimeField(max_length=6, default=timezone.now)

我的序列化程序

class SpaceObjectSerializer(serializers.HyperlinkedModelSerializer):
  class Meta:
    model = SpaceObject
    fields = ['norad', 'object_type', 'name', 'period', 'inclination', 'apogee', 'perigee', 'rcs_size', 'tle_1', 'tle_2', 'last_updated']

我的看法

class SpaceObjectViewSet(viewsets.ModelViewSet):
  queryset = SpaceObject.objects.all()
  serializer_class = SpaceObjectSerializer
  permission_classes = [permissions.AllowAny]

我试着运行它,但还是有问题

pip install djangorestframework-jsonapi['django-filter']

有办法解决这个问题吗?我试着按照文档操作,但没有成功。

wfauudbj

wfauudbj1#

我希望你一切都好。首先,你需要确保你已经安装了Django-Filter。用下面的命令检查一下。

pip install 'django-filter'

接下来,将django-filter添加到INSTALLED_APPS中。

INSTALLED_APPS = [

    'rest_framework',
    'rest_framework_json_api',
    'django_filters',

]

然后,在View类中,您应该设置字段和过滤器属性,如下例所示:

class SpaceObjectViewSet(viewsets.ModelViewSet):
  queryset = SpaceObject.objects.all()
  serializer_class = SpaceObjectSerializer
  permission_classes = [permissions.AllowAny]

  filterset_fields = {
         'name': ('exact', 'icontains', 'iexact', 'contains',),
  }

调用API进行如下精确过滤:

http://localhost:8000/api/space_objects/?filter[name]=THEOS

并要求提供以下类似的容器:

http://localhost:8000/api/space_objects/?filter[name.icontains]=THEOS

并保持与容器相似。

相关问题