问题描述:

  • 在model中设置了help_text后,但并没有在drf的doc中显示

解决方法:

  • 重载filter_for_field方法然后将help_text加到extra中
    • 例:
    class UserFilter(rest_framework.FilterSet):
        class Meta:
            model = User
            fields = '__all__'
    
        @classmethod
        def filter_for_field(cls, field, field_name, lookup_expr='exact'):
            filter_class = super().filter_for_field(field, field_name, lookup_expr)
            filter_class.extra['help_text'] = field.help_text
            return filter_class
    
    
  • 也可以直接修改django_filters.rest_framework下面的FilterSet, 重写filter_for_field方法, 不用每个filter都写了,继承他就ok了, 不过这样的缺点就是部署时需要修改对应环境的FilteSet, 可以通过直接下载django_filters保存到项目里来,再修改, 然后就不用担心了
class FilterSet(filterset.FilterSet):
    ...
    @classmethod
    def filter_for_field(cls, field, field_name, lookup_expr='exact'):
        filter_class = super().filter_for_field(field, field_name, lookup_expr)
        filter_class.extra['help_text'] = field.help_text
        return filter_class

参考链接: https://github.com/carltongibson/django-filter/issues/754