Total count of objects in Django Model

11,181

Solution 1

There's nothing wrong with Exprator's answer, but one alternative is to use the built in length template filter:

<h2>Total number of words and phrases entered: {{ bytes|length }}</h2>

If you're not planning to iterate over the bytes queryset you could also call count on it directly in the template:

<h2>Total number of words and phrases entered: {{ bytes.count }}</h2>

That will force a second database query, though, so only do that if you aren't otherwise causing bytes to be evaluated.

The decision of what to put in the view and what to do with template filters/no-arg methods is more a question of style than a hard and fast rule. Erring on the side of using the view is usually right, here it's simple enough that I might just do it in the template.

Solution 2

You've got a few different options... the most common ways to get the total number of model instances I have seen are:

my_total = len(Byte.objects.filter())

or, without having to run the full query:

my_total = Byte.objects.count()

Here's a link to the resource doc for 1.11: https://docs.djangoproject.com/en/1.11/topics/db/aggregation/#cheat-sheet

Solution 3

def byte_list(request):
    byte= Byte.objects.count()
    bytes = Byte.objects.order_by('text')
    return render(request, 'cloudapp/byte_list.html', {'bytes': bytes,'byte':byte})

And in template

 {{ byte }}
Share:
11,181
Ron Raney
Author by

Ron Raney

I love music and computing.

Updated on June 04, 2022

Comments

  • Ron Raney
    Ron Raney almost 2 years

    Using Django ~=1.11 and Python 3.6

    I am a beginner! Every answer I've found online for my question is more advanced than what I'm looking for.

    Here's my model:

    class Byte(models.Model):
        text = models.CharField(max_length=30)
    
        def __str__(self):
            return self.text  
    

    Here's my view:

    def byte_list(request):
        bytes = Byte.objects.order_by('text')
        return render(request, 'cloudapp/byte_list.html', {'bytes': bytes})
    

    Here's my template:

    {% block content %}
        <div class="total">
            <h2>Total number of words and phrases entered: {{ byte.count }}</h2>
        </div>
    <hr>
    {% for byte in bytes %}
        <div class="byte">
            <h2>{{ byte.text }}</h2>
        </div>
    {% endfor %}
    {% endblock %}
    

    This allows the creation "Byte" objects in the /admin, with only one field - a small text field. Right now, the template simply displays a list of all the objects created.

    Question/Problem: I'd like to display the total number/count of objects that have been created for the Byte model. In the template, I have a tag {{ byte.count }} to display this.

    I've tried using count() and Aggregation, but not sure how to work those into my model/view/template. I'm looking for the most simple and up-to-date way to accomplish this, whether it's using a method or @property in the model, or some type of query set in the view.

  • Peter DeGlopper
    Peter DeGlopper almost 7 years
    Generally sound, but the docs recommend loading the queryset into memory and using len if you're going to need the queryset anyway. count() is faster than len if you're not loading it, but here bytes will be needed so {'bytes': bytes, 'byte_count': len(bytes)} probably comes out faster. docs.djangoproject.com/en/1.11/ref/models/querysets/#count
  • Ron Raney
    Ron Raney almost 7 years
    Thanks. How would I render this in the template? If I make this change, it shows nothing.
  • Peter DeGlopper
    Peter DeGlopper almost 7 years
    Whatever key you use in the context dict (byte in @Exprator's version, byte_count in my comment) will be available as a context variable, so just {{ byte_count }} should work.
  • Ron Raney
    Ron Raney almost 7 years
    Thanks. Would this be placed in the model or the view?
  • Douglas
    Douglas almost 7 years
    Definitely in the view, where you actually want to do something with the returned value... you could, for example, have 50 instances, then run the above in your view and pass the variable my_total into your template, or anything else, to say "you have {{ my_total }} Byte objects".
  • Ron Raney
    Ron Raney almost 7 years
    Thank you! I forgot about filtering in the template. The thing is... I want to use this value in another calculation. I forgot to mention this.
  • Exprator
    Exprator almost 7 years
    Sorry forgot to mention in template it will be {{ byte }}. Will update the ans
  • Ron Raney
    Ron Raney almost 7 years
    If I wanted to use this value in a calculation, could I do that? If so, would this "count" need to be done in the model as a method or property?
  • Exprator
    Exprator almost 7 years
    You can do this in the view and do the calculation what you need to do in the view and send it to the template
  • Ron Raney
    Ron Raney almost 7 years
    Thanks. My eyes are opening wider.
  • Ron Raney
    Ron Raney almost 7 years
    Thanks for your help!
  • Peter DeGlopper
    Peter DeGlopper almost 7 years
    If you're doing calculations with it, definitely do it in the view.