From 0384cc3aff094f972d1db4d2c3040c55a863eddb Mon Sep 17 00:00:00 2001 From: Matt Westcott Date: Tue, 21 Apr 2020 19:26:11 +0100 Subject: [PATCH] Add bulk_to_python method to the base Block class --- wagtail/core/blocks/base.py | 8 ++++++++ wagtail/core/blocks/list_block.py | 11 ++--------- wagtail/core/blocks/stream_block.py | 8 ++------ 3 files changed, 12 insertions(+), 15 deletions(-) diff --git a/wagtail/core/blocks/base.py b/wagtail/core/blocks/base.py index 648eafda26..5c5585b5c5 100644 --- a/wagtail/core/blocks/base.py +++ b/wagtail/core/blocks/base.py @@ -213,6 +213,14 @@ class Block(metaclass=BaseBlock): """ return value + def bulk_to_python(self, values): + """ + Apply the to_python conversion to a list of values. The default implementation simply + iterates over the list; subclasses may optimise this, e.g. by combining database lookups + into a single query. + """ + return [self.to_python(value) for value in values] + def get_prep_value(self, value): """ The reverse of to_python; convert the python value into JSON-serialisable form. diff --git a/wagtail/core/blocks/list_block.py b/wagtail/core/blocks/list_block.py index 8aa67ae967..942e8fa659 100644 --- a/wagtail/core/blocks/list_block.py +++ b/wagtail/core/blocks/list_block.py @@ -134,15 +134,8 @@ class ListBlock(Block): return result def to_python(self, value): - # If child block supports bulk retrieval, use it. - if hasattr(self.child_block, 'bulk_to_python'): - return self.child_block.bulk_to_python(value) - - # Otherwise recursively call to_python on each child and return as a list. - return [ - self.child_block.to_python(item) - for item in value - ] + # 'value' is a list of child block values; use bulk_to_python to convert them all in one go + return self.child_block.bulk_to_python(value) def get_prep_value(self, value): # recursively call get_prep_value on children and return as a list diff --git a/wagtail/core/blocks/stream_block.py b/wagtail/core/blocks/stream_block.py index 34209633f9..b8dd244b37 100644 --- a/wagtail/core/blocks/stream_block.py +++ b/wagtail/core/blocks/stream_block.py @@ -390,12 +390,8 @@ class StreamValue(Sequence): raw_value = self.stream_data[i] type_name = raw_value['type'] child_block = self.stream_block.child_blocks[type_name] - if hasattr(child_block, 'bulk_to_python'): - self._prefetch_blocks(type_name, child_block) - return self._bound_blocks[i] - else: - value = child_block.to_python(raw_value['value']) - block_id = raw_value.get('id') + self._prefetch_blocks(type_name, child_block) + return self._bound_blocks[i] else: try: type_name, value, block_id = self.stream_data[i]