【问题标题】:pass all fields of model in django filter backend在 django 过滤器后端传递模型的所有字段
【发布时间】:2017-05-23 08:55:50
【问题描述】:

有什么方法可以pass all the fields of a model to django filter backend 而不显式传递 search_fields 和 filter_fields 中的字段名称

我制作了一个通用视图集,它序列化传递给它的模型的所有字段,但我在应用通用过滤器时遇到了问题

例如,

class UserListView(generics.ListAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    filter_backends = (filters.SearchFilter,)
    search_fields = ('username', 'email')

在上面的代码中,我们显式传递了search_fields,但在我的代码中,我不能显式传递字段,因为每次都可能传递不同的模型。

【问题讨论】:

    标签: django django-rest-framework django-filter django-filters


    【解决方案1】:

    我认为这样做并不明智,因为某些字段会泄露敏感信息,但您可以尝试从模型中传递所有字段:

    class UserListView(generics.ListAPIView):
        queryset = User.objects.all()
        serializer_class = UserSerializer
        filter_backends = (filters.SearchFilter,)
        search_fields = [f.name for f in User._meta.get_fields()]
    

    Here are the docs 用于使用get_fields:

    Options.get_fields(include_parents=True, include_hidden=False)[来源]

    返回与模型关联的字段元组。 get_fields() 接受两个可用于控制哪些字段的参数 返回:

    • include_parents True 默认情况下。递归地包括在父级上定义的字段 类。如果设置为False,get_fields() 将只搜索字段 直接在当前模型上声明。直接来自模型的字段 从抽象模型或代理类继承被认为是 本地,而不是父级。
    • include_hidden False 默认情况下。如果设置为True,get_fields() 将 包括用于支持其他字段功能的字段。这 还将包括任何具有related_name 的字段(例如 ManyToManyField 或 ForeignKey) 以“+”开头。

    【讨论】:

      【解决方案2】:

      https://docs.djangoproject.com/en/1.10/ref/models/meta/

      class UserListView(generics.ListAPIView):
          queryset = User.objects.all()
          serializer_class = UserSerializer
          filter_backends = (filters.SearchFilter,)
          search_fields = [field.name for field in User._meta.fields]  
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-05
        • 1970-01-01
        • 2013-06-15
        • 2020-03-19
        • 2022-10-05
        • 2011-12-03
        相关资源
        最近更新 更多