2

I have a streamfield which is working, and has data in, the code I wrote to do this looks something like:

class NewYearBlock(blocks.StructBlock):
  year = blocks.IntegerBlock(verbose_name="Year (the year this data is rolling into)")
  holidayRollover = blocks.FloatBlock(verbose_name="How many hours are rolling over")
  overtimeRollover = blocks.FloatBlock(verbose_name="How many hours are rolling over")
  class Meta:
      icon = 'user'

and

newyearStream = StreamField([
    ('newyear', NewYearBlock()),
], blank=True)

What I would like to do is to append an item to this streamfield via some code, I know how to replace the item with the below (which works)

employeeModel.newyearStream = newyearStream
employeeModel.save()

But this replaces what already exists.

I was then thinking I could loop over the existing stream, and then create a new object to save, but when I try to do that I receive TypeError: cannot unpack non-iterable StreamChild object so I looked at the type, and see it is <class 'wagtail.core.blocks.stream_block.StreamValue'>

Can anyone help point me in the right direction to either loop through the stream and get my results out, or a better way to append to my streamField.

Thanks for your time helping, Dan

retrodans
  • 123
  • 1
  • 1
  • 9
  • Can you share your current code for looping over the stream? That's essentially the correct way to do it, so seeing your code would help to figure out what's going wrong. – gasman Nov 20 '20 at 17:04
  • @gasman thanks, on rewriting the loop to send to you, I have stumbled across `.value['xxx']` which appears to work, so my loop looks more like ``` for x in fullNYStream: print(x.value['year']) ``` I will test more on Monday – retrodans Nov 20 '20 at 19:20
  • @retrodans did you end up finding a way to save it? I'm trying to do the exact same thing and struggling with the save. I have tried using .value['xxx'] – squidg Nov 29 '22 at 23:43

1 Answers1

0

From the docs: "A StreamField’s value behaves as a list, and blocks can be inserted, overwritten, and deleted before saving the instance back to the database. A new item can be written to the list as a tuple of (block_type, value)."

# Append a rich text block to the stream
from wagtail.rich_text import RichText
my_page.body.append(('paragraph', RichText("<p>And they all lived happily ever after.</p>")))

# Save the updated data back to the database
my_page.save()
Fuchsi
  • 127
  • 5