Skip to content

Offering up some code: PageAwareParentalManyToManyField #190

@rgs258

Description

@rgs258

In cases where a ParentalManyToManyField is defined on a mixin class that's to be inherited in both Wagtail Pages and raw Django Models, the PageAwareParentalManyToManyField may be used. I don't remember where I got this code from (or if I created it or not!), but it works great and I thought I'd share:

class PageAwareParentalManyToManyField(ParentalManyToManyField):
    """
    A ManyToManyField that is aware of if it is being used on a page or a non-page
    model. When uses on a page, it will perform as a ParentalManyToManyField,
    otherwise it will perform as a regular ManyToManyField.
    """

    def contribute_to_class(self, cls, name, **kwargs):
        if issubclass(cls, (AbstractPage, PageBase)):
            super().contribute_to_class(cls, name, **kwargs)
        else:
            super(ParentalManyToManyField, self).contribute_to_class(cls, name,
                                                                     **kwargs)

    def value_from_object(self, obj):
        if isinstance(self.model, (AbstractPage, PageBase)):
            return super().value_from_object(obj)
        else:
            return super(ParentalManyToManyField, self).value_from_object(obj)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions