views:

52

answers:

2

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

+2  A: 

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 model called mymodelinstance, you can do mymodelinstance.my_custom_method().

If you want to call it on the class, you need to define a classmethod. You can do this with the @classmethod decorator on your method. Note that by convention the first parameter to a classmethod is cls, not self. 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() or objects.get(), then your best bet is to define a custom Manager and add your method there. Then you will be able to do model.objects.my_custom_method(). Again, see the Django documentation on Managers.

Daniel Roseman
Helped me alot, thanks!
Izz ad-Din Ruhulessin
A: 

If you are implementing a Signal for your model it does not necessarily need to be defined in the model class only. You can define it outside the class and pass the class name as the parameter to the connect function.

However, in your case you need the model object to access the method.

anand