Implement bulk_to_python on ListBlock

pull/6469/head
Matt Westcott 2020-04-21 21:01:10 +01:00
rodzic bd8418d009
commit 47faf79308
2 zmienionych plików z 30 dodań i 0 usunięć

Wyświetl plik

@ -1,3 +1,5 @@
import itertools
from django import forms
from django.core.exceptions import ValidationError
from django.forms.utils import ErrorList
@ -137,6 +139,22 @@ class ListBlock(Block):
# '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 bulk_to_python(self, values):
# 'values' is a list of lists of child block values; concatenate them into one list so that
# we can make a single call to child_block.bulk_to_python
lengths = [len(val) for val in values]
raw_values = list(itertools.chain.from_iterable(values))
converted_values = self.child_block.bulk_to_python(raw_values)
# split converted_values back into sub-lists of the original lengths
result = []
offset = 0
for sublist_len in lengths:
result.append(converted_values[offset:offset + sublist_len])
offset += sublist_len
return result
def get_prep_value(self, value):
# recursively call get_prep_value on children and return as a list
return [

Wyświetl plik

@ -2342,6 +2342,18 @@ class TestListBlockWithFixtures(TestCase):
self.assertSequenceEqual(pages, expected_pages)
def test_bulk_to_python(self):
block = blocks.ListBlock(blocks.PageChooserBlock())
with self.assertNumQueries(1):
result = block.bulk_to_python([[4, 5], [], [2]])
self.assertEqual(result, [
[Page.objects.get(id=4), Page.objects.get(id=5)],
[],
[Page.objects.get(id=2)],
])
class TestStreamBlock(WagtailTestUtils, SimpleTestCase):
def test_initialisation(self):