Home > database >  Django - count how many objects are in self
Django - count how many objects are in self

Time:05-31

I have a very simple model with the following details:

class ExclusiveUser(models.Model):
    exclusivepass = models.CharField(max_length=4, primary_key=True, editable=False)
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    date_of_birth = models.DateField(null=True)
    date_of_birth = models.DateField(null=True)
    age = models.IntegerField(editable=False)

    def save(self,*args, **kwargs):
        today = date.today()

        self.exclusivepass = exclusivepass_gen(self.exclusivepass.all().count())
        self.age = today.year - self.date_of_birth.year - ((today.month, today.day) < (self.date_of_birth.month, self.date_of_birth.day))

        super().save(*args, **kwargs)

exclusivepass_gen is a simple utils.py method for generating a unique exclusivepass

def exclusivepass_gen(pass_count):
    pass_next = 0
    pass_limit = 101

    if pass_count < pass_limit:
        pass_next = pass_count   1

    return ('E'   "{:03d}".format(pass_next))

I'm trying to get the count of all objects in the table to pass to exclusivepass_gen to generate the next number, but I get the following error when i do: 'ExclusiveUser' object has no attribute 'all'

How can i count all objects in the model to pass to exclusivepass_gen method?

CodePudding user response:

You would query the db in the save method like so:

class ExclusiveUser(models.Model):
    exclusivepass = models.CharField(max_length=4, primary_key=True, editable=False)
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    date_of_birth = models.DateField(null=True)
    date_of_birth = models.DateField(null=True)
    age = models.IntegerField(editable=False)

    def save(self,*args, **kwargs):
        today = date.today()

        # Get qs
        qs_passes = ExclusiveUser.objects.all().count()

        self.exclusivepass = exclusivepass_gen(qs_passes)
        self.age = today.year - self.date_of_birth.year - ((today.month, today.day) < (self.date_of_birth.month, self.date_of_birth.day))

        super().save(*args, **kwargs)

You can't get the record count of your database using a method on the model itself as this only refers to the current instance of the class, not your db.

Note: In case you delete records you might end up with pass duplicates as the count may return the same amount < twice

  • Related