Add bulk_to_python method to the base Block class

pull/6469/head
Matt Westcott 2020-04-21 19:26:11 +01:00
rodzic ba6f94def1
commit 0384cc3aff
3 zmienionych plików z 12 dodań i 15 usunięć

Wyświetl plik

@ -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.

Wyświetl plik

@ -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

Wyświetl plik

@ -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]