0

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?

2
  • Can you call the method super(MyModel, self).save(*args, **kwargs) before you call self.do_something()? So just switch the two so that the object will get created first. Commented May 25, 2012 at 23:05
  • I have tried that--it doesn't seem to help. Also, I'd like to make sure the 'do_something' completes successfully before I save the model. Commented May 26, 2012 at 19:15

1 Answer 1

1

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) ... 
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks. Should be good now. It's hard debugging made up code!
Welcome. If that answer solved your problem, consider clicking checkmark to mark this answer Accepted.
That really doesn't solve the actual problem. We'll see what else comes in.
That's what I'd like to avoid really. Obviously I can take all my methods outside the model.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.