Izz*_*sin 12 python django methods model
用例如
class model(models.Model)
....
def my_custom_method(self, *args, **kwargs):
#do something
Run Code Online (Sandbox Code Playgroud)
当我尝试在pre_save,save,post_save等过程中调用此方法时,Python引发了一个TypeError; 未绑定的方法.
如何添加自定义模型方法,可以像model.objects.get()等一样执行?
编辑:尝试使用super(model, self).my_custom_method(*args, **kwargs)但在这种情况下Python说该模型没有属性my_custom_method
Dan*_*man 30
你怎么称呼这种方法?您已经定义了一个实例方法,该方法只能在类的实例上调用,而不能在类本身上调用.换句话说,一旦你有一个model被调用的实例mymodelinstance,你就可以做到mymodelinstance.my_custom_method().
如果要在类上调用它,则需要定义一个classmethod.您可以使用@classmethod方法中的装饰器执行此操作.请注意,按照惯例,classmethod的第一个参数cls不是self.有关classmethod的详细信息,请参阅Python文档.
但是,如果你真正想做的是添加一个执行查询集级操作的方法,比如objects.filter()或objects.get(),那么最好的办法是定义一个自定义管理器并在那里添加你的方法.然后你就可以做到model.objects.my_custom_method().再次,请参阅关于Managers 的Django文档.