如果 DRF 和 Django 过滤器中没有提供过滤,则返回空页面

Posted

技术标签:

【中文标题】如果 DRF 和 Django 过滤器中没有提供过滤,则返回空页面【英文标题】:Return Empty Page if There's No Filtering Provided in DRF and Django Filters 【发布时间】:2021-12-03 12:08:57 【问题描述】:

我有一个 ViewSet 如下:

class EntryViewSet(viewsets.ModelViewSet):
    queryset = Entry.objects.all()
    serializer_class = EntrySerializer
    filter_backends = [DjangoFilterBackend, OrderingFilter]
    filterset_class = EntryFilterSet
    ordering_fields = ["created_at", "last_update"]
    ordering = "created_at"

...和一个 FilterSet 定义了几个我可以过滤的字段:

class EntryFilterSet(django_filters.FilterSet):
    class Meta:
        model = models.Entry
        fields = [
            "content",
            # and other fields
        ]

我已将我的EntryViewSet 与 DRF 的 DefaultRouter 连接到 /api/entries/,列表视图自动命名为 api:entry-list

所以,/api/entries/ 返回:


  "count": 100,
  "next": "http://localhost:8000/api/entries/?format=json&p=2",
  "previous": null,
  "results": [
    
      "pk": "6Kqpyak",
      "created_at": "2021-10-13T13:28:17.410883Z",
      "last_update": "2021-10-13T13:28:17.410898Z",
      "content": "Start investment begin nice feeling. Travel sea mind teacher could. Within act series effort crime.",
      "content_html": "<p>Start investment begin nice feeling. Travel sea mind teacher could. Within act series effort crime.</p>",
      "author": 1,
      "title": 
        "pk": "6Kqpyak",
        "created_at": "2021-10-13T13:28:17.408026Z",
        "label": "republican attack computer recently though guy.",
        "redirects_to": null,
        "recent_count": 0,
        "last_update": "2021-10-13T13:28:17.416822Z"
      
    ,
    
      "pk": "1ozyMzx",
      "created_at": "2021-10-13T13:28:17.532635Z",
      "last_update": "2021-10-13T13:28:17.532649Z",
      "content": "School establish partner. Establish possible who let. Impact health exactly particular note.",
      "content_html": "<p>School establish partner. Establish possible who let. Impact health exactly particular note.</p>",
      "author": 2,
      "title": 
        "pk": "1ozyMzx",
        "created_at": "2021-10-13T13:28:17.531007Z",
        "label": "produce six while act.",
        "redirects_to": null,
        "recent_count": 0,
        "last_update": "2021-10-13T13:28:17.535188Z"
      
    ,
    
      "pk": "RJ2Ypz6",
      "created_at": "2021-10-13T13:28:17.649090Z",
      "last_update": "2021-10-13T13:28:17.649102Z",
      "content": "Later doctor nearly somebody threat contain. System most citizen surface hand. Whatever behind administration reflect.",
      "content_html": "<p>Later doctor nearly somebody threat contain. System most citizen surface hand. Whatever behind administration reflect.</p>",
      "author": 3,
      "title": 
        "pk": "RJ2Ypz6",
        "created_at": "2021-10-13T13:28:17.647544Z",
        "label": "man family inside free room project around federal.",
        "redirects_to": null,
        "recent_count": 0,
        "last_update": "2021-10-13T13:28:17.651709Z"
      
    ,
    
      "pk": "Z52x9q6",
      "created_at": "2021-10-13T13:28:17.766830Z",
      "last_update": "2021-10-13T13:28:17.766843Z",
      "content": "Event more prepare more paper why. Shake represent carry easy.",
      "content_html": "<p>Event more prepare more paper why. Shake represent carry easy.</p>",
      "author": 4,
      "title": 
        "pk": "Z52x9q6",
        "created_at": "2021-10-13T13:28:17.765145Z",
        "label": "within make check seat provide street enough could.",
        "redirects_to": null,
        "recent_count": 0,
        "last_update": "2021-10-13T13:28:17.769486Z"
      
    ,
    
      "pk": "RGqd8qp",
      "created_at": "2021-10-13T13:28:17.883725Z",
      "last_update": "2021-10-13T13:28:17.883738Z",
      "content": "Out imagine school. Service will authority decision.",
      "content_html": "<p>Out imagine school. Service will authority decision.</p>",
      "author": 5,
      "title": 
        "pk": "RGqd8qp",
        "created_at": "2021-10-13T13:28:17.882053Z",
        "label": "have seek letter data operation of.",
        "redirects_to": null,
        "recent_count": 0,
        "last_update": "2021-10-13T13:28:17.886221Z"
      
    ,
    
      "pk": "oVaDYzL",
      "created_at": "2021-10-13T13:28:18.000127Z",
      "last_update": "2021-10-13T13:28:18.000140Z",
      "content": "Effect hear budget involve hand. Southern skin eight degree marriage hit. Management explain finish young.",
      "content_html": "<p>Effect hear budget involve hand. Southern skin eight degree marriage hit. Management explain finish young.</p>",
      "author": 6,
      "title": 
        "pk": "oVaDYzL",
        "created_at": "2021-10-13T13:28:17.998689Z",
        "label": "edge could official raise it social.",
        "redirects_to": null,
        "recent_count": 0,
        "last_update": "2021-10-13T13:28:18.002121Z"
      
    ,
    
      "pk": "Qw2Abq5",
      "created_at": "2021-10-13T13:28:18.115996Z",
      "last_update": "2021-10-13T13:28:18.116009Z",
      "content": "Entire avoid fill view buy those. Activity fund woman.",
      "content_html": "<p>Entire avoid fill view buy those. Activity fund woman.</p>",
      "author": 7,
      "title": 
        "pk": "Qw2Abq5",
        "created_at": "2021-10-13T13:28:18.114276Z",
        "label": "three never hold free power camera plan.",
        "redirects_to": null,
        "recent_count": 0,
        "last_update": "2021-10-13T13:28:18.118433Z"
      
    ,
    
      "pk": "mOz79q9",
      "created_at": "2021-10-13T13:28:18.232557Z",
      "last_update": "2021-10-13T13:28:18.232570Z",
      "content": "Their wrong man prepare participant seek exist. Cause political white year early far arrive. Step during bring result book. Idea off each hotel.",
      "content_html": "<p>Their wrong man prepare participant seek exist. Cause political white year early far arrive. Step during bring result book. Idea off each hotel.</p>",
      "author": 8,
      "title": 
        "pk": "mOz79q9",
        "created_at": "2021-10-13T13:28:18.231008Z",
        "label": "high boy customer continue.",
        "redirects_to": null,
        "recent_count": 0,
        "last_update": "2021-10-13T13:28:18.235055Z"
      
    ,
    
      "pk": "odq0Pqp",
      "created_at": "2021-10-13T13:28:18.349485Z",
      "last_update": "2021-10-13T13:28:18.349499Z",
      "content": "Sport hard writer suddenly officer head. Stand ok standard if some natural.",
      "content_html": "<p>Sport hard writer suddenly officer head. Stand ok standard if some natural.</p>",
      "author": 9,
      "title": 
        "pk": "odq0Pqp",
        "created_at": "2021-10-13T13:28:18.347777Z",
        "label": "professor sign kid today.",
        "redirects_to": null,
        "recent_count": 0,
        "last_update": "2021-10-13T13:28:18.351944Z"
      
    ,
    
      "pk": "Pyz9ezE",
      "created_at": "2021-10-13T13:28:18.467119Z",
      "last_update": "2021-10-13T13:28:18.467133Z",
      "content": "Account control arm example edge world.",
      "content_html": "<p>Account control arm example edge world.</p>",
      "author": 10,
      "title": 
        "pk": "Pyz9ezE",
        "created_at": "2021-10-13T13:28:18.465434Z",
        "label": "ago current politics direction happy.",
        "redirects_to": null,
        "recent_count": 0,
        "last_update": "2021-10-13T13:28:18.469393Z"
      
    ,
    
      "pk": "jV2mGay",
      "created_at": "2021-10-13T13:28:18.583407Z",
      "last_update": "2021-10-13T13:28:18.583420Z",
      "content": "Soldier street deal which become rather most interesting. Involve job brother become race. Former who then better per eight garden. Particular reduce easy report physical study edge.",
      "content_html": "<p>Soldier street deal which become rather most interesting. Involve job brother become race. Former who then better per eight garden. Particular reduce easy report physical study edge.</p>",
      "author": 11,
      "title": 
        "pk": "jV2mGay",
        "created_at": "2021-10-13T13:28:18.581806Z",
        "label": "else free reason there ask morning good east.",
        "redirects_to": null,
        "recent_count": 0,
        "last_update": "2021-10-13T13:28:18.585613Z"
      
    ,
    
      "pk": "Qeqe5q1",
      "created_at": "2021-10-13T13:28:18.700883Z",
      "last_update": "2021-10-13T13:28:18.700911Z",
      "content": "Option exactly call speech. Kitchen sport build collection talk.",
      "content_html": "<p>Option exactly call speech. Kitchen sport build collection talk.</p>",
      "author": 12,
      "title": 
        "pk": "Qeqe5q1",
        "created_at": "2021-10-13T13:28:18.698691Z",
        "label": "race someone senior.",
        "redirects_to": null,
        "recent_count": 0,
        "last_update": "2021-10-13T13:28:18.703568Z"
      
    ,
    
      "pk": "QEq8Yam",
      "created_at": "2021-10-13T13:28:18.818029Z",
      "last_update": "2021-10-13T13:28:18.818043Z",
      "content": "Billion development something usually condition big high. Teacher trip pick religious decide report ground.",
      "content_html": "<p>Billion development something usually condition big high. Teacher trip pick religious decide report ground.</p>",
      "author": 13,
      "title": 
        "pk": "QEq8Yam",
        "created_at": "2021-10-13T13:28:18.816374Z",
        "label": "guess present provide rate stage door cold.",
        "redirects_to": null,
        "recent_count": 0,
        "last_update": "2021-10-13T13:28:18.820609Z"
      
    ,
    
      "pk": "93qOXaN",
      "created_at": "2021-10-13T13:28:18.934904Z",
      "last_update": "2021-10-13T13:28:18.934918Z",
      "content": "From Democrat rock pretty great former. Continue expert success perhaps. Conference she live interview know.",
      "content_html": "<p>From Democrat rock pretty great former. Continue expert success perhaps. Conference she live interview know.</p>",
      "author": 14,
      "title": 
        "pk": "93qOXaN",
        "created_at": "2021-10-13T13:28:18.933225Z",
        "label": "during full executive require.",
        "redirects_to": null,
        "recent_count": 0,
        "last_update": "2021-10-13T13:28:18.937446Z"
      
    ,
    
      "pk": "pg2Enqy",
      "created_at": "2021-10-13T13:28:19.053488Z",
      "last_update": "2021-10-13T13:28:19.053502Z",
      "content": "Election memory security make address morning campaign. Whom may hear can.",
      "content_html": "<p>Election memory security make address morning campaign. Whom may hear can.</p>",
      "author": 15,
      "title": 
        "pk": "pg2Enqy",
        "created_at": "2021-10-13T13:28:19.051383Z",
        "label": "discover picture trade against huge dinner bill so.",
        "redirects_to": null,
        "recent_count": 0,
        "last_update": "2021-10-13T13:28:19.056058Z"
      
    ,
    
      "pk": "YgaR3zl",
      "created_at": "2021-10-13T13:28:19.170756Z",
      "last_update": "2021-10-13T13:28:19.170770Z",
      "content": "Live politics pull card choose project. Right say share security.",
      "content_html": "<p>Live politics pull card choose project. Right say share security.</p>",
      "author": 16,
      "title": 
        "pk": "YgaR3zl",
        "created_at": "2021-10-13T13:28:19.169057Z",
        "label": "usually mention down interest fast simple.",
        "redirects_to": null,
        "recent_count": 0,
        "last_update": "2021-10-13T13:28:19.173290Z"
      
    ,
    
      "pk": "Evzryax",
      "created_at": "2021-10-13T13:28:19.287340Z",
      "last_update": "2021-10-13T13:28:19.287354Z",
      "content": "Challenge do drop this. Data follow including.",
      "content_html": "<p>Challenge do drop this. Data follow including.</p>",
      "author": 17,
      "title": 
        "pk": "Evzryax",
        "created_at": "2021-10-13T13:28:19.285621Z",
        "label": "behind how for call go particular democratic area.",
        "redirects_to": null,
        "recent_count": 0,
        "last_update": "2021-10-13T13:28:19.289753Z"
      
    ,
    
      "pk": "Jo2bn29",
      "created_at": "2021-10-13T13:28:19.404715Z",
      "last_update": "2021-10-13T13:28:19.404729Z",
      "content": "Great drug water military game second choose item. Real soldier system energy south child itself. Contain throw attention cup support suddenly piece.",
      "content_html": "<p>Great drug water military game second choose item. Real soldier system energy south child itself. Contain throw attention cup support suddenly piece.</p>",
      "author": 18,
      "title": 
        "pk": "Jo2bn29",
        "created_at": "2021-10-13T13:28:19.403005Z",
        "label": "back record region poor in class room.",
        "redirects_to": null,
        "recent_count": 0,
        "last_update": "2021-10-13T13:28:19.407063Z"
      
    ,
    
      "pk": "7OzXkan",
      "created_at": "2021-10-13T13:28:19.522027Z",
      "last_update": "2021-10-13T13:28:19.522040Z",
      "content": "Increase firm machine. Fast learn expert indeed center young per.",
      "content_html": "<p>Increase firm machine. Fast learn expert indeed center young per.</p>",
      "author": 19,
      "title": 
        "pk": "7OzXkan",
        "created_at": "2021-10-13T13:28:19.520464Z",
        "label": "small even scene worker involve few.",
        "redirects_to": null,
        "recent_count": 0,
        "last_update": "2021-10-13T13:28:19.524342Z"
      
    ,
    
      "pk": "rAaZVaj",
      "created_at": "2021-10-13T13:28:19.638963Z",
      "last_update": "2021-10-13T13:28:19.638977Z",
      "content": "Sport Republican image on make third. Process particular support chair very share few important. Man war apply position cultural science hundred.",
      "content_html": "<p>Sport Republican image on make third. Process particular support chair very share few important. Man war apply position cultural science hundred.</p>",
      "author": 20,
      "title": 
        "pk": "rAaZVaj",
        "created_at": "2021-10-13T13:28:19.637345Z",
        "label": "like western natural theory right audience four.",
        "redirects_to": null,
        "recent_count": 0,
        "last_update": "2021-10-13T13:28:19.641106Z"
      
    
  ]

...过滤也有效。但是,这不是我想要的行为。如果没有提供过滤,我希望此端点返回一个空页面。如下:


  "count": 0,
  "next": "http://localhost:8000/api/entries/?format=json&p=2",
  "previous": null,
  "results": []

我怎样才能实现这种行为?


环境

django ^2.2 djangorestframework ^3.12.4 django 过滤器 ^21.1

【问题讨论】:

【参考方案1】:

由于过滤适用于 URL 参数,因此您可以检查它们。如果它们是空的,你可以返回一个空的查询集。

您可以在ModelViewSet 上的get_queryset 上实现此行为。只需覆盖以下方法:

    def get_queryset(self):
        if not bool(self.request.GET):
            return Entry.objects.none()

        return Entry.objects.all()

但请记住,这会检查 URL 参数是否为空。如果您出于其他原因使用 URL 参数,这可能会导致意外行为。

【讨论】:

以上是关于如果 DRF 和 Django 过滤器中没有提供过滤,则返回空页面的主要内容,如果未能解决你的问题,请参考以下文章

Django DRF序列化器或视图中的多表过滤

是否过滤 Django Rest Framework (DRF) 中的代码示例优化问题

DRF ---- 过滤组件 分页组件 过滤组件插件使用

在 Django (DRF) 中使用外部 API 进行基于令牌的身份验证

Django DRF视图过滤ManyToMany查询集

Django(69)最好用的过滤器插件Django-filter