如何使用django-filters重命名(在API中公开)过滤器字段名称?

正如问题所述 – 我正在尝试重命名我的API中公开的过滤器字段名称.

我有以下型号:

class Championship(Model):
    ...

class Group(Model):
    championship = ForeignKey(Championship, ...)

class Match(Model):
    group = ForeignKey(Group, ...)

我在REST API中公开了所有这些模型.我为Match模型定义了filter_fields:

class MatchViewSet(ModelViewSet):
    filter_fields = ['group__championship']
    ...

这样,我可以过滤特定锦标赛的比赛(测试和工作):

curl /api/matches/?group__championship=1

是否可以为暴露的过滤器使用某种别名,以便我可以使用以下内容:

curl /api/matches/?championship=1

在这种情况下,冠军将成为group__championship的别名?

pip冻结返回:

django-filter==0.15.2
(...)

我也尝试使用ModelChoiceFilter和自定义查找方法实现自定义FilterSet:

class MatchFilterSet(FilterSet):
    championship = ModelChoiceFilter(method='filter_championship')

    def filter_championship(self, queryset, name, value):
        return queryset.filter(group__championship=value)

    class Meta:
        model = Match
        fields = ['championship']

有了观点:

class MatchViewSet(ModelViewSet):
    filter = MatchFilterSet
    (...)

但没有运气.甚至从未调用过filter_championship方法.

最佳答案 您需要在字段类型的django_filters中提供模型字段作为名称.我正在考虑你试图按冠军头衔过滤.

class MatchFilterSet(FilterSet):
    championship = django_filters.NumberFilter(name='group__championship_id')

    class Meta:
        model = Match
        fields = ['championship']
点赞