DEV Community

Adam Mateusz Brożyński
Adam Mateusz Brożyński

Posted on

Wagtail: both way relation between models

This example uses wagtail-autocomplete panel (follow install notes there) and works with Wagtail 5.2.1 (latest stable).

Create a relation model:

from django.db import models
from modelcluster.fields import ParentalKey

class NewsPageCalendarPageRelation(models.Model):
    news = ParentalKey('pages.NewsPage', on_delete=models.CASCADE, related_name='news')
    calendar = ParentalKey('pages.CalendarPage', on_delete=models.CASCADE, related_name='calendar')

    # This ensures that relations are not doubled
    class Meta:
        unique_together = ('news', 'calendar')
Enter fullscreen mode Exit fullscreen mode

And now two models using this relation:

from wagtailautocomplete.edit_handlers import AutocompletePanel
from modelcluster.fields import ParentalManyToManyField

class CalendarPage(Page):
    news = ParentalManyToManyField(
        'pages.NewsPage', 
        through=NewsPageCalendarPageRelation,
        blank=True,
        )

    # ...

    content_panels = [
    # ...
        AutocompletePanel('news', target_model='pages.CalendarPage'),
    ]
Enter fullscreen mode Exit fullscreen mode
from wagtailautocomplete.edit_handlers import AutocompletePanel
from modelcluster.fields import ParentalManyToManyField

class NewsPage(Page):
    calendar = ParentalManyToManyField(
        'pages.CalendarPage', 
        through=NewsPageCalendarPageRelation,
        blank=True,
        )

    # ...

    content_panels = [
    # ...        
        AutocompletePanel('calendar',target_model='pages.NewsPage'),
    ]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)