Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Offering up some code: PageAwareParentalManyToManyField #190

Open
rgs258 opened this issue Sep 27, 2024 · 0 comments
Open

Offering up some code: PageAwareParentalManyToManyField #190

rgs258 opened this issue Sep 27, 2024 · 0 comments

Comments

@rgs258
Copy link

rgs258 commented Sep 27, 2024

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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant