[SOLVED] Django – call Manager with multiple inherited classes

Issue

This Content is from Stack Overflow. Question asked by Octavian Niculescu

So I have this class that helps me override the update method of a queryset:

class QuerySetUpdateOverriden(QuerySet, object):
    def update(self, *args, **kwargs):
        super().update(*args, **kwargs)
        if hasattr(self, 'method_from_object'):
            self.method_from_object()
            return

and here’s my class where I use it:

class MyObject:
    objects = QuerySetUpdateOverriden.as_manager()
    def method_from_object(self):
        print("called")

the print statement is never reached.

And I get why – the objects field doesn’t inherit MyObject too.

So, the question is – how can I make it inherit MyObject so method_from_object will be called?

Thanks.



Solution

You test if self has a method called ‘method_from_object’, but your QuerySetUpdateOverriden has no method call like this. And MyObject does not inherit from QuerySetUpdateOverriden.

This code would be work i think:

class MyObjectManager(QuerySetUpdateOverriden.as_manager()):

    def method_from_object(self):
        print("called")


class MyObject(models.Model):
    objects = QuerySetUpdateOverriden.as_manager()



This Question was asked in StackOverflow by Octavian Niculescu and Answered by Lucas Grugru It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?