当我以自动递增的形式保存'序列号'时出现以下错误 错误
last_id = self.objects.all().aggregate(largest=models.Max('sequence_number'))['largest']
File "/home/abc/new/virtual/local/lib/python2.7/site-packages/django/db/models/manager.py", line 252, in __get__
raise AttributeError("Manager isn't accessible via %s instances" % type.__name__)
AttributeError: Manager isn't accessible via Section instances
这是我的models.py
class Section(models.Model):
section_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
req = models.ForeignKey('requst.Request', null=True, blank=True)
title = models.CharField(max_length=100)
sequence_number = models.FloatField( default=1)
created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True)
updated_at = models.DateTimeField(auto_now=True, null=True, blank=True)
created_by = models.IntegerField(default=0)
updated_by = models.IntegerField(default=0)
def __unicode__(self):
return self.title
def save(self, *args, **kwargs):
if self._state.adding:
last_id = self.objects.all().aggregate(largest=models.Max('sequence_number'))['largest']
if last_id is not None:
self.sequence_number = last_id + 1
super(Section, self).save(*args, **kwargs)
答案 0 :(得分:3)
由于错误明确指出,您不允许在模型实例上访问模型的管理器,您必须通过模型类本身访问它。
这样做的干净方法是使用type()
,即替换:
self.objects.all()
与
type(self).objects.all()
现在模型继承相当罕见,如果你在这种情况下没有使用它,你可以使用以下方法对模型类进行硬编码:
Section.objects.all()
话虽如此,您的代码并非防弹 - 您可以轻松地让多个进程同时调用Section.save()
的竞争条件。