You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何限制Strawberry GraphQL Django在GraphiQL界面的过滤选项

Strawberry GraphQL Django v0.31 过滤选项精简方案

冗余过滤项的产生根源,是@strawberry.django.filters.filter装饰器传入lookups=True时,会为所有字段自动挂载全量内置查找规则,其中就包含isNull、regex这类多数业务场景用不到的选项。可以通过以下三种方式自定义暴露的过滤项,精简GraphiQL界面:

  • 方案1:关闭类级全量lookup,逐字段配置允许的过滤规则
    把装饰器的lookups参数改为False,关闭自动生成全量规则的逻辑,此时auto类型字段默认仅生成exact精确匹配规则;如果需要给单个字段开放更多查找类型,通过filter.field显式指定允许的lookup即可,关联外键的过滤器也会同步继承精简配置:

    from strawberry.django import filters
    
    @filters.filter(models.Client, lookups=False)
    class ClientFilter:
        id: auto
        name: auto = filters.field(lookups=["exact", "icontains"])
    
    @filters.filter(models.Matter, lookups=False)
    class MatterFilter:
        id: auto
        client: 'ClientFilter'
        category: auto = filters.field(lookups=["exact", "icontains"])
    
  • 方案2:全局覆写各字段类型的默认lookup集合
    如果项目里过滤器较多,不想逐个类修改,可以在Strawberry初始化配置中,针对不同Django字段类型设置默认开放的查找规则,从根源移除无意义选项:

    from django.db import models as django_models
    from strawberry_django import filters
    
    # 为不同字段类型指定默认允许的lookup,移除不需要的规则
    filters.default_lookups[django_models.IntegerField] = ["exact", "in"]
    filters.default_lookups[django_models.CharField] = ["exact", "icontains", "istartswith"]
    filters.default_lookups[django_models.ForeignKey] = ["exact", "in"]
    

    配置完成后,即使过滤器类传入lookups=True,也只会生成上述列表中指定的过滤项。

  • 方案3:直接排除指定的冗余lookup
    如果不需要精细调整每个字段/类型的规则,只是想去掉某几个通用的冗余选项,可以直接在装饰器上用exclude参数指定要全局排除的lookup名称,改造成本最低:

    @filters.filter(models.Client, lookups=True, exclude=["isnull", "regex", "iregex"])
    class ClientFilter:
        id: auto
        name: auto
    
    @filters.filter(models.Matter, lookups=True, exclude=["isnull", "regex", "iregex"])
    class MatterFilter:
        id: auto
        client: 'ClientFilter'
        category: auto
    

默认生成的冗余过滤选项效果参考:
过滤选项效果图

调整配置后重启服务刷新GraphiQL页面,即可看到过滤项已按配置精简,不会再出现无业务意义的选项。

内容的提问来源于stack exchange,提问作者ccsv

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 17:25:03