1

I am using a third party application and i wish to override the save() method of the original model to validate some data.

class CustomState(State):
    class Meta:
        proxy = True

    def save(self, *args, **kwargs):
        print('hellooo in save method of state')
        super(State, self).save(*args, **kwargs)

However the code snippet above does not run.

Therefore my question is is there a way to override the save method of a model ? Or if thats not possible , is there a way to add in validation before the third party model instance is created?

neowenshun
  • 860
  • 1
  • 7
  • 21
  • A proxy model does not override anything of the original model. A proxy model "uses the original" table, and "attaches different behavior". If you thus make a `CustomState().save()`, then it will trigger this `.save()` method. – Willem Van Onsem Jun 30 '20 at 10:32
  • Ah i see , okay im getting a better understanding. However , the model creation is within the third party application by itself. As i don't wish to patch it is there a way to modify the behavior of the third party model when it is saved? – neowenshun Jun 30 '20 at 10:34
  • unless you use *monkey patching* (https://stackoverflow.com/questions/5626193/what-is-monkey-patching), no, and this is also a bit *risky* and inellegant. – Willem Van Onsem Jun 30 '20 at 10:37

1 Answers1

2

the issue has nothing to do with the fact that your Model is proxy but the wrong way how you call the parent super().save():

class CustomState(State):
    class Meta:
        proxy = True

    def save(self, *args, **kwargs):
        print('hellooo in save method of state')

        # The wrong way to call super
        # super(State, self).save(*args, **kwargs)

        super(CustomState, self).save(*args, **kwargs)

have a look at this tutorial, topic A super() Deep Dive

cizario
  • 3,995
  • 3
  • 13
  • 27