Indexing of streamfield data in Wagtail
Install the package
pip install wagtail-streamfield-index
Add to your installed apps
INSTALLED_APPS = [
...
"streamfieldindex",
...
]
Run python manage.py streamfieldindex
to index all pages.
After indexing, your database will contain one IndexEntry
for every block found in a page model.
The index will keep itself up-to-date every time a page is saved.
If you would like to see a list of indexed blocks in your wagtail admin interface, you can register the modeladmin
Make sure modeladmin app is installed:
INSTALLED_APPS = [
...
"wagtail.contrib.modeladmin",
...
]
Register the IndexEntryAdmin
in a wagtail_hooks.py file:
from wagtail.contrib.modeladmin.options import modeladmin_register
from streamfieldindex.modeladmin import IndexEntryAdmin
modeladmin_register(IndexEntryAdmin)
from streamfieldindex.models import IndexEntry
block_name
The name that you gave to your block in the streamfield definition.
e.g "author" or "heading" in the following example:
my_field = StreamField([
('author', AuthorBlock()),
('heading', CharBlock()),
use_json_field=True
])
For items inside list blocks, the block_name
is set to the list block name with ":item" appended, since individual items inside a list block do not have a name.
block_value
The string value of the block, in the form that it is stored in the streamfield. StructBlock
, StreamBlock
and ListBlock
s have an empty string as the block_value since you can inspect the contents of those blocks by looking at their sub-blocks.
If you have a complex block type such as an ImageChooser block, see the get_bound_block()
method
block_path
A slash-delimited path to the location of the block within the streamfield.
E.g. if block_path = 5/author/title
5
. The 6th block in the streamfield.author
. The 6th block is namedauthor
.title
. Thetitle
sub-block ofauthor
.
field_name
The name of the field where the block was found.
page
The page where the block was found.
get_bound_block()
Returns a Wagtail BoundBlock
instance of the block. See the Wagtail docs for explaination of BoundBlock
s.
If you had an author
block and wanted to find all usage of that block:
from streamfieldindex.models import IndexEntry
for index_entry in IndexEntry.objects.filter(block_name="author"):
print(index_entry.page.id) # Print the page ID where the block is found
print(index_entry.field_name) # Print the field where the block is found
print(index_entry.block_path) # Print a slash-separated path to the block inside the field
- Clone the repo
git clone https://github.com/nhsuk/wagtail-streamfield-index.git
- Install dependencies
pip install .[testing,linting]
If you are having issues in installing, it may be of use to use an environment tool like virtualenv
black .
flake8 .
pytest