sprksh
sprksh

Reputation: 2404

Function call on individual field save in django

Say I have a model:

class Workplace(models.Model):
    name = models.CharField(max_length=255)
    ...
    office_mail_id = models.EmailField(null=True, blank=True)

What I want is whenever the value of email is changed and the object is saved, a function should be run which would save the value of that field to other models (say Emails)

Now, this can be done in many ways like creating a custom save function which would call the email saving function or otherwise making a custom function and save emails through it:

def set_email(self, email):
    self.office_mail_id = email
    self.save()
    # do whatever i want
    return

What i want to know is that is there a simpler way to do this so that whenever i run

company.office_mail_id = request.POST.get('email')
company.save()

in a view, the function may be run saving it to other models as i want

The problem here is that I am not saving all fields individually but making a dictionary and saving all fields based on key and values like this as there are so many fields:

for key in dictionary:
    setattr(workplace, key, dictionary[key])
workplace.save()

What can be the best way to do it?

Upvotes: 0

Views: 175

Answers (1)

DeepSpace
DeepSpace

Reputation: 81664

Just override save in Workplace:

def save(self, *args, **kwargs):
   # do whatever you need, save other models etc.. 
   super().save(*args, **kwargs))  # or super(Workplace, self).save(*args, **kwargs)
                                   # if Python 2

Upvotes: 1

Related Questions