Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python/Django: Adding custom model methods?

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

like image 942
Izz ad-Din Ruhulessin Avatar asked Oct 13 '10 07:10

Izz ad-Din Ruhulessin


1 Answers

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.

like image 74
Daniel Roseman Avatar answered Sep 24 '22 01:09

Daniel Roseman