Swagger布尔参数值True / False而不是true / false和django_filters

时间:2017-05-15 19:02:09

标签: django swagger swagger-ui django-filter django-filters

Swagger UI以'true / false'形式提交布尔参数,而django filter boolean field则需要True / False(大写)。因此,当我通过swagger查询时,字段 is_published 无效。

{{api_url}}/api/v1/games/?limit=10&offset=0&is_published=true
{{api_url}}/api/v1/games/?limit=10&offset=0&is_published=false

过滤字段定义为

is_published = BooleanFilter(name='versions__is_published')

完整定义

class GameFilter(FilterSet):
    """Custom filter for ``GameViewSet``.

    Defines custom filter for ``genres`` field (based on TaggableManager).

    """

    is_published = BooleanFilter(name='versions__is_published')

    class Meta:
        model = Game

        fields = {
            'platforms':  ['exact'],
            'ages':       ['exact'],
            'developers': ['exact'],
            'genres':     ['exact'],
            'created':    ['gt', 'lt']
        }

Swagger定义方法

get:
  summary: Get list of games
  operationId: getGamesList
  parameters:
    - $ref: '../../parameters.yaml#/Offset'
    - $ref: '../../parameters.yaml#/Limit'
    - $ref: '../../parameters.yaml#/PlatformsFilter'
    - $ref: '../../parameters.yaml#/DevelopersFilter'
    - $ref: '../../parameters.yaml#/GenresFilter'
    - $ref: '../../parameters.yaml#/AgesFilter'
    - $ref: '../../parameters.yaml#/SearchFilter'
    - $ref: '../../parameters.yaml#/Order'
    - name: is_published
      in: query
      type: boolean
      required: false
      default: true

enter image description here

1 个答案:

答案 0 :(得分:1)

<强>溶液

基础django_filters.FilterSet旨在与vanilla Django视图一起使用。如果您正在使用DRF创建API,则应使用django_filters.rest_framework.FilterSet,因为它使用稍微不同的过滤器集,这些过滤器更适合在API中使用。在这种情况下,BooleanFilter接受小写的真/假值。

调整导入后:

from django_filters import ModelMultipleChoiceFilter
from django_filters.rest_framework import BooleanFilter, FilterSet