[Answered ]-Django extend custom manager at runtime. Mixin style?

2👍

You could do something like:

if hasattr(cls, 'objects'):
    if cls.objects.__class__ == models.Manager:
        # default manager, override
        cls.add_to_class('objects', TranslationManager()
    else:
        # there is a custom manager, don't override
        class CombinedManager(cls.objects.__class__, TranslationManager):
            pass
        cls.add_to_class('objects', CombinedManager())

But, you need to be extremely cautious about the namespace, in particular conflicts that might occur between the original manager and your TranslationManager. In general, it’s best to leave it to the end-user to determine whether or not they want their custom manager to include the TranslationManager as well.

I’d recommend simply putting it in the documentation that TranslationManager will only be added as the default manager if a custom manager isn’t present. Otherwise, the user should have their custom manager inherit from TranslationManager to gain that functionality.

Leave a comment