Django: create model object with incremented version number
I have a model for example:
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 similar below, but somehow avoid the race conditions and make this atom:
e = Example(title='test')
e.version = Example.objects.filter(title=e.title).aggregate(Max('version'))['version__max']+1
e.save()
PS. I am using Django 1.8
+3
source to share
1 answer
I am overriding .save()
like this:
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()
(Customize your checkout history if needed)
0
source to share