Ostap Khl
Ostap Khl

Reputation: 183

Overriding save method in another class

I have a few models in project(modelA, modelB, modelC), and I want to override the save method in each so it has functionality applicable to all.

So I make something like this for a model:

class modelA(CustomClass, models.Model):
    ......

class CustomClass():
    def save(self, *args, **kwargs):
        # do something
        # and now I want to call modelA.save() method
        super(modelA, self).save(*args, **kwargs)
        # super is used here as example

The question is if it is even possible, and if so, how can I do this ?

Upvotes: 0

Views: 1008

Answers (3)

trojjer
trojjer

Reputation: 639

I tend to use mixins (composition-based multiple inheritance) for cases like this, but it's your call. It could be as simple as declaring a CustomSaveMixin class which inherits from object, with the save override you want. This would let you keep in place the base Model subclassing for the methods you don't need to override. For example:

class CustomSaveMixin(object):
    def save(self, *args, **kwargs):
        # ...
        # If you're preserving existing Django save hooks (most likely).
        super(CustomSaveMixin, self).save(*args, **kwargs)

class ExampleModel(models.Model, CustomSaveMixin):
    # ...

However, I haven't tried this approach (subclassing object), but I know it works for class based views. The official docs suggest declaring a mixin class that extends models.Model, but I'd try both approaches. https://docs.djangoproject.com/en/1.9/topics/db/models/#multiple-inheritance

Upvotes: 0

ohrstrom
ohrstrom

Reputation: 2970

class CustomClass(models.Model):

    def save(self, *args, **kwargs):
        # do things needed generally 2.)
        super(CustomClass, self).save(*args, **kwargs)


class ModelA(CustomClass):

    def save(self, *args, **kwargs):
        # do things specific for ModelA 1.)
        super(ModelA, self).save(*args, **kwargs)
        # do things specific for ModelA 3.)

numbers before brackets show execution order in case of saving ModelA

Upvotes: 0

Sayse
Sayse

Reputation: 43330

Yes, just define your save method in the custom class and make sure you call the base method in any further overriding of the save method.

By default, the model uses the models.Model implementation of save. When you call super (via super(CustomClass, self)..) you will be invoking the usual saving behaviour.


Note the above depends on modelA inheriting from custom class which inherits from Model which I initially thought it was doing..

class modelA(CustomClass):
    ......

class CustomClass(models.Model):
    ....

Upvotes: 2

Related Questions