忽略 Marshmallow 中无效的嵌套多个字段的实例

Omit instances of an invalidated nested many field in Marshmallow

marshmallow 中是否可以省略验证失败但父级不失败的嵌套模式实例?例如,一个 Atom 提要可以有很多条目。如果一个条目缺少必填字段,是否可以省略该条目,以便提要及其正确解析的条目通过验证而没有失败的条目?

from marshmallow import Schema


class Feed(Schema):
    """Atom/RSS feed."""
    ...
    entries = fields.Nested('Entry', many=True)
    ...

class Entry(Schema):
    """Article of an Atom/RSS feed."""
    ...
    title = fields.String(required=True)
    link = fields.Url(required=True)
    ...

验证 Feed 之前

...
"entries": [
  {
    "title": "Title A",
    "link": "http://httpbin.org/status/200"
  },
  {
    "title": "",
    "link": "",

  },
  {
    "title": "Title C",
    "link": "http://httpbin.org/status/200"
  },
]
...

验证 Feed 后

...
"entries": [
  {
    "title": "Title A",
    "link": "http://httpbin.org/status/200"
  },
  {
    "title": "Title C",
    "link": "http://httpbin.org/status/200"
  },
]
...

pre_load 装饰器可用于过滤嵌套字段,但我假设每个嵌套模式被反序列化两次:一次在 pre_load 期间,一次在加载期间。

class Feed(Schema):
    ...
    entries = fields.Nested('Entry', many=True)
    ...

    @pre_load
    def filter_entries(self, data, **kwargs):
        schema = Entry()
        filtered = []
        for entry in data['entries']:
            try:
                filtered.append(schema.load(entry))
            except ValidationError:
                continue
        data['entries'] = filtered
        return data