Reputation: 1970
I'm trying to override the save method of one of my models. Within that save method I would like to use another method of the model, like this:
class MyModel(models.Model):
name = models.CharField(max_length=255)
def do_something(self):
pass
def save(self,*args, **kwargs):
self.do_something()
super(MyModel, self).save(*args, **kwargs)
This doesn't work because when django executes the save, the object is a generic ModelBase class and not my subclass of ModeBase. So I get:
unbound method do_something() must be called with MyModel instance as first argument (got ModelBase instance instead)
What is the right way to do this?
Upvotes: 0
Views: 451
Reputation: 2724
You should put args
and kwargs
to overridden save()
method too:
class MyModel(models.Model):
name = models.CharField(max_length=255)
def do_something(self):
pass
def save(self, *args, **kwargs):
self.do_something()
super(MyModel, self).save(*args, **kwargs)
You also forgot self
parameter in do_something()
!
UPDATE
I don't quite understand your problem. If you want to call unbound method do_something
, define it outside the class MyModel
with one and just call it from save()
like `do_something(self):
class MyModel(class.Model):
def save(self, *args, **kwargs):
do_something(self)
super(MyModel, self).save(*args, **kwargs)
def do_someting(my_model_instance):
assert isinstance(my_model_instance, MyModel)
...
Upvotes: 1