Scott Warren
Scott Warren

Reputation: 1601

Django Model - Incrementing Version Number like Grails

We are looking at moving from Grails to Django..

In Grails every Domain Class (Model in Django) has an Integer field called "version" when the Domain class is Updated it is incremented by 1.

(Grails/Hibernate also use this field to check that the Row has not been updated by the user since the data was loaded. But that is another issue.)

How can I add an Integer field called version which is incremented each time the model is Saved/Updated in the database?

Upvotes: 0

Views: 447

Answers (1)

xthestreams
xthestreams

Reputation: 169

overwrite the save method of the model

class Increment(models.Model):
    # data you want to store

    # the version bit
    version = Models.IntegerField(default=0)

    def save(self, *args, **kwargs):
        self.version = self.version + 1
        super(Model, self).save(*args, **kwargs)

Upvotes: 1

Related Questions