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)
In cases where a
ParentalManyToManyFieldis defined on a mixin class that's to be inherited in both Wagtail Pages and raw Django Models, thePageAwareParentalManyToManyFieldmay 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: