user8866053
user8866053

Reputation:

Count Number of Entries in a Column Django

I have a counter object defined as

class Counter(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    counter_text = models.IntegerField(default=100)

I want to count exactly how many counter objects exist in django.

I am using this as an average, so if there is a better way to average a column, please tell me. Thanks in advance!

Upvotes: 0

Views: 876

Answers (2)

edthrn
edthrn

Reputation: 1172

To get an iterable of all the instances of your model, the all() method is what you need (see doc)

>>> MyModel.objects.all()   # returns a queryset

If you want to count the numbers of Counter instances in your database, thank to the ability of chaining queries (see doc), you can just do:

>>> Counter.objects.all().count()  # returns an integer

Upvotes: 3

Tim Woocker
Tim Woocker

Reputation: 1996

If you want to count the amount of Counter rows, you can do it like this:

Counter.objects.all().count()

This will return the amount of rows as an int.

Upvotes: 2

Related Questions