Using for example
class model(models.Model)
....
def my_custom_method(self, *args, **kwargs):
#do something
When I try to call this method during pre_save, save, post_save etc, Python raises a TypeError; unbound method.
How can one add custom model methods which can be executed in the same way like model.objects.get(), etc?
Edit: tried using super(model, self).my_custom_method(*args, **kwargs) but in that case Python says that model does not have attribute my_custom_method
How are you calling this method? You have defined an instance method, which can only be called on an instance of the class, not the class itself. In other words, once you have an instance of
modelcalledmymodelinstance, you can domymodelinstance.my_custom_method().If you want to call it on the class, you need to define a classmethod. You can do this with the
@classmethoddecorator on your method. Note that by convention the first parameter to a classmethod iscls, notself. See the Python documentation for details on classmethod.However, if what you actually want to do is to add a method that does a queryset-level operation, like
objects.filter()orobjects.get(), then your best bet is to define a custom Manager and add your method there. Then you will be able to domodel.objects.my_custom_method(). Again, see the Django documentation on Managers.