Django:使用增加的版本号创建模型对象

时间:2015-06-11 19:07:33

标签: python django django-models django-orm

我有模特,例如:

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

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

我想在下面实现类似的东西,但不知何故避免竞争条件并使其成为原子:

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

PS。我正在使用Django 1.8

1 个答案:

答案 0 :(得分:0)

我这样覆盖.save()

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()

(根据您的验证故事进行调整)