Carlo Cogni
Carlo Cogni

Reputation: 67

How to return the total number of items from django model?

I would like to return the total number of items I have in a databse from the following simple model:

class EquipmentType(models.Model):
    type        = models.CharField(max_length=100, unique=True)
    description = models.CharField(max_length=250, default='')
    date_posted = models.DateTimeField(auto_now_add=True)
    # auto_now = timezone.now
    image       =models.ImageField(default='default.jpeg', upload_to='equipment/equipment_type')
    active      =models.BooleanField(default=True)

Below the model I've defined the following function:

@property
def get_total_num(self):
    total = 0
    equipmentType = EquipmentType.objects.all()
    for type in equipmentType:
        total = total + 1
    return total

which I call in the template with a simple for testing:

  <h3>numero tot: {{get_total_num}}</h3>

The db has about 44 objects, thus I would expect the function, once called, to return that number. Unfortunately it returns nothing (just the string 'numero tot').

This is the class based view I'm using:

class EquipmentType_ListView(LoginRequiredMixin, ListView):
    model               = EquipmentType
    template_name       = 'equipment/equipmentType_list.html' # default = <app>/<model>_<viewtype>.html
    context_object_name = 'obj_list' 
    
    def get_queryset(self):
        
        return EquipmentType.objects.filter(active = True).order_by('type')

Any suggestion on what is actually missing?

Thank you very much.

Carlo

Upvotes: 0

Views: 659

Answers (1)

Arjun Shahi
Arjun Shahi

Reputation: 7330

There is no necesaary to write the extra function in the model.

You can simply use the count or length in your templates like this.

 <h3>numero tot: {{obj_list.count}} 
 </h3>

 OR {{obj_list|length}}

If you want to do it from the view

total_objs_count = EquipmentType.objects.count()

Upvotes: 1

Related Questions