[PYTHON] Override save method in django-models

Overwrite Model's save method if you want something to be done just before inserting into the database

class Event(models.Model):

    class Meta:
        unique_together = ('name', 'held_date')

    id = models.CharField(primary_key=True, max_length=20)
    name = models.CharField(max_length=8)
    held_date = models.DateField()

    def save(self, **kwargs):
        u"""Create the value of the primary key just before inserting"""
        self.id = "%s@%s" % (str(self.held_date), self.name)
        super(Event, self).save(**kwargs)

When I overwrite django's save (), the manager's method may or may not call it.

Call me

Don't call me

It's surprisingly called. There is also signals.pre_save, but it's the same as doing it, and save overwriting is more explicit.

Recommended Posts

Override save method in django-models
Simplex method (simplex method) in Python
Private method in python
I touched Wagtail (1) and let's override the save method.
Template Method pattern in Java
Implement method chain in Python
Suppressing method overrides in Python
Save Time type in SQLAlchemy
Save the binary file in Python
Try implementing extension method in python
Save a specific variable in tensorflow.session
Implemented label propagation method in Python
Simulate Monte Carlo method in Python
Hash method (open address method) in Python
Save a YAML-formatted file in PyYAML