在字段上过滤不应用实际的 fitler 集

Filtering on fields doesn't apply the actual fitler set

扩展BaseAPIEndpoint on a custom page model exposes its pages through the api, which is great, however, when I try to apply a field filter, it is not applied, and the response returns all pages regardless. The documentation没有提到这个。

例如:

endpoints.py

from wagtail.api.v2.endpoints import BaseAPIEndpoint
from app.models import MyPageClass

class MyPageClassAPIEndpoint(BaseAPIEndpoint):
    refname= MyPageClass
    model = refname

api.py:

from wagtail.api.v2.router import WagtailAPIRouter
from .endpoints import MyPageClassAPIEndpoint

# Create the router. "wagtailapi" is the URL namespace
api_router = WagtailAPIRouter('wagtailapi')
api_router.register_endpoint('refname', MyPageClassAPIEndpoint)

如果我在调用端点时尝试添加过滤器:

http://localhost:8000/api/v2/refname/?id=6

回复将 return 所有与我的模型关联的记录。

{
"meta": {
    "total_count": 2
},
"items": [
    {
        "id": 6,
        "meta": {
            "type": "app.MyPageClass",
            "detail_url": "http://localhost/api/v2/pages/6/"
        }
    },
    {
        "id": 7,
        "meta": {
            "type": "app.MyPageClass",
            "detail_url": "http://localhost/api/v2/pages/7/"
        }
    }
  ]
}

如何在扩展 BaseAPIEndpoint 的同时实现端点过滤 class?

您需要从 wagtail.api.v2.filters 导入 FieldsFilter Class,然后将其附加到自定义端点 Class 的 filter_backends,如下所示:

from wagtail.api.v2.endpoints import BaseAPIEndpoint
from wagtail.api.v2.filters import FieldsFilter
from app.models import MyPageClass

class MyPageClass(BaseAPIEndpoint):
    refname= MyPageClass
    model = refname
    BaseAPIEndpoint.filter_backends.append(FieldsFilter)

这样做之后,您的端点现在将接受对字段的过滤。

http://localhost:8000/api/v2/refname/?id=6

{
"meta": {
    "total_count": 1
},
"items": [
    {
        "id": 6,
        "meta": {
            "type": "projects.ProjectTaskPage",
            "detail_url": "http://localhost/api/v2/pages/6/"
        }
    }
  ]

}