Python/Django: Adding custom model methods?
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.