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

标签 python django rest django-filter

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

我有以下型号:

class Championship(Model):
    ...

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

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

我已经在 REST API 中公开了所有这些模型。我已经定义了 filter_fieldsMatch模型:
class MatchViewSet(ModelViewSet):
    filter_fields = ['group__championship']
    ...

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

curl /api/matches/?group__championship=1



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

curl /api/matches/?championship=1



哪里championship在这种情况下将是 group__championship 的别名?
pip freeze返回:
django-filter==0.15.2
(...)

我也试过实现自定义 FilterSetModelChoiceFilter和自定义查找方法:
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 中提供模型字段作为名称。我正在考虑您正在尝试按冠军 ID 进行过滤。

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

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

关于python - 如何使用 django-filters 重命名(在 API 中公开)过滤器字段名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39992515/

相关文章:

delphi - 无状态 HTTP session 中的进度反馈

rest - GraphQL 和微服务

python - 我想在条目中输入一个值,按下按钮并将该值保存在 var 中,并使用该值创建一个 .txt 文件,但它不起作用

python selenium 单击链接

python - 有条件地设置 DataFrame 的非空值

python - 如何通过 mod-wsgi 使用 FCKEditor 的图像上传和浏览器?

python - 从 pandas 数据框中删除已知的异常值

python - Sphinx add_config_value 不添加变量

django - 名称错误 : name 'TypeError' is not defined in Apache logs

web-services - RESTful用户身份验证服务