Reputation: 349
I got following error when i used to save 'sequence number' in automatic incremented form error
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
this is my 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)
Upvotes: 3
Views: 3400
Reputation: 77902
As the error clearly states, you are not allowed to access a model's manager on a model instance, you have to access it thru the model class itself.
The clean way to do so is to use type()
, ie replace:
self.objects.all()
with
type(self).objects.all()
Now model inheritance being rather rare, if you don't have a use for it in this case, you can just hardcode the model class instead using:
Section.objects.all()
This being said, your code is not bulletproof - you can easily have race conditions with multiple processes calling Section.save()
concurrently.
Upvotes: 4