问题描述
我有一个带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\"].","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"])
表示法进行过滤。
重要说明
您可以在任何地方放置注册代码片段,但是, 确保在服务器启动时执行该代码。