What is the difference in these two implementations of creating a carousel? They both seem to do the same thing, however one has Foreign Keys explicitly defined. The first implementation can easily be plugged in by calling it, meanwhile the second implementation has to be connected to a model via a ParentalKey. Essentially, which is the better option to to implement a carousel for display on a homepage?
class ImageCarouselBlock(blocks.StructBlock):
image = ImageChooserBlock()
caption = blocks.TextBlock(required=False)
page = PageChooserBlock()
class Meta:
icon = 'image'
class CarouselItem(LinkFields):
image = models.ForeignKey(
'wagtailimages.Image',
null=True,
blank=True,
on_delete=models.SET_NULL,
related_name='+'
)
link_url = models.models.ForeignKey(
'wagtailcore.Page',
null=True,
blank=True,
on_delete=models.SET_NULL,
related_name='+'
)
caption = models.CharField(max_length=255, blank=True)
panels = [
ImageChooserPanel('image'),
FieldPanel('link_url'),
FieldPanel('caption'),
MultiFieldPanel(LinkFields.panels, "Link"),
]
class Meta:
abstract = True
The main benefit of the StructBlock / StreamField approach is the ability to mix different block types in the sequence - so, for example, you could define ImageCarouselBlock
and VideoCarouselBlock
to have a carousel that mixes images and videos.
If you only have one kind of object in the sequence, there's not much to choose between the two approaches. However, using a child model / InlinePanel is arguably nicer from a data modelling point of view, as it ensures that each object gets a real database entry (unlike StreamField where the data is stored in a single JSON field), meaning that you can run database queries against that data. (It's a bit hard to find a non-contrived example of why you'd want to do this with a carousel - but you could say things like "give me all of the NewsPages that include image X in their carousel".)