【问题标题】:How to use MultipleChoiceFilter in graphene-django?如何在graphene-django中使用MultipleChoiceFilter?
【发布时间】:2021-02-07 13:59:31
【问题描述】:

我有一个带有 graphql 端点的 Django 应用程序。我需要能够通过某个字段的多个值一次过滤对象。

我有以下石墨烯方案:

class ChannelFilter(FilterSet):
    type = MultipleChoiceFilter(choices=Channel.TYPES)

    class Meta:
        model = Channel
        fields = ['type']


class ChannelNode(DjangoObjectType):

    class Meta:
        model = Channel
        filter_fields = ['type']
        interfaces = (relay.Node,)


class Query(graphene.ObjectType):
    channels = DjangoFilterConnectionField(
        ChannelNode, filterset_class=ChannelFilter
    )


schema = graphene.Schema(query=Query)

然后我尝试了以下 graphql 查询来过滤我的对象:

query {
  channels(type: "BOT") {
    edges {
      node {
        id
      }
    }
  }
}

结果出现如下错误:

{
  "errors": [
    {
      "message": "['{\"type\": [{\"message\": \"Enter a list of values.\", \"code\": \"invalid_list\"}]}']",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "path": [
        "channels"
      ]
    }
  ],
  "data": {
    "channels": null
  }
}
query {
  channels(type: ["BOT"]) {
    edges {
      node {
        id
      }
    }
  }
}

结果出现如下错误:


{
  "errors": [
    {
      "message": "Argument \"type\" has invalid value [\"BOT\"].\nExpected type \"String\", found [\"BOT\"].",
      "locations": [
        {
          "line": 2,
          "column": 18
        }
      ]
    }
  ]
}

如何正确使用MultipleChoiceFilter?谢谢

【问题讨论】:

    标签: django graphql django-filter relay graphene-django


    【解决方案1】:

    您可能需要将表单字段转换器注册为

    import graphene
    from graphene_django.forms.converter import convert_form_field
    from django_filters.fields import MultipleChoiceField
    
    
    @convert_form_field.register(MultipleChoiceField)
    def convert_multiple_choice_filter_to_list_field(field):
        return graphene.List(graphene.String, required=field.required)

    然后使用 channels(type: ["BOT"]) 符号进行过滤。

    重要提示

    您可以将注册码 sn-p 放在任何地方,但是,确保它在服务器启动时被执行。

    【讨论】:

      猜你喜欢
      • 2018-03-31
      • 2019-09-22
      • 2017-11-11
      • 2018-10-29
      • 2021-11-09
      • 2017-03-15
      • 2020-10-23
      • 2021-01-21
      • 1970-01-01
      相关资源
      最近更新 更多