[Answer]-Django – counting objects in database inside model declaraton

1👍

This is actually something you would want to do on a manager, rather than the model itself. The model should represent, and perform actions for, an individual instance. Whereas the manager represents, and performs actions for a collection of instances. So in this case you might want something like:

from django.db import models

class ItemManager(models.Manager):

    def next_number(self):
        return self.count() + 1

class Item(models.Model):
    number = models.IntegerField()

    objects = ItemManager()

That being said, I could see this leading to a lot of data integrity issues. Imagine the scenario:

  • 4 items are created, with numbers 1, 2, 3, 4
  • Item 2 gets deleted
  • 1 new item is created; this item now has a number of 4, giving you a duplicate

Edit:

The above approach will work only for pre-generating ‘number’, such as:

Iteam.objects.create(number=Iteam.objects.get_number(), name='foo')

In order to have it work as an actual default value for the field, you would need to use a less savory approach, such as:

from django.db import models

class Iteam(models.Model):
    name = models.CharField()
    number = models.IntegerField(default=lambda: Iteam.get_next_number())

    @classmethod
    def get_next_number(cls):
        return cls.objects.count() + 1

I would still warn against this approach, however, as it still could lead to the data integrity issues mentioned above.

Leave a comment