如何在石墨烯django中使用MultipleChoiceFilter



我有一个带有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?感谢

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

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"])表示法进行筛选。

重要提示

您可以将注册代码片段放在任何地方,但请确保它在服务器启动时执行

相关内容

  • 没有找到相关文章

最新更新