Django: Create model object with increased version number

2.4k views Asked by At

I have Model, e.g.:

class Example(models.Model):
   title = models.SlugField()
   version = models.PositiveSmallIntegerField(default=0)
   content = models.TextField(blank=True)

   class Meta:
       unique_together = (
           ('title', 'version'),
       )

I would like to achieve something like that below but somehow avoid race conditions and make this atomic:

e = Example(title='test')
e.version = Example.objects.filter(title=e.title).aggregate(Max('version'))['version__max']+1
e.save()

PS. I'm using Django 1.8

1

There are 1 answers

3
AstraLuma On

I'm overriding .save() like so:

class Example(models.Model):
    title = models.SlugField()
    version = models.PositiveSmallIntegerField()
    content = models.TextField(blank=True)
    
    class Meta:
        unique_together = (
            ('title', 'version'),
        )
    
    def _highest_version(self):
        return Example.objects.filter(title=self.title).aggregate(Max('version'))['version__max'] or 0
    
    def save(self):
        if self.version is None:
            self.version = self._highest_version() + 1
        return super().save()

(Adjust as necessary for your validation story)