Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count the number of rows in a database table in Django

Tags:

I have database created by Django model, where status and id and username are the fields of the table Messages.

I need to count the number of rows where status value= 0 for a particular username.

This is my incomplete code:

Message_me = Messages.objects.get(username='myname') 
like image 638
Friend Avatar asked Mar 26 '13 11:03

Friend


People also ask

What does count do in Django?

Use Django's count() QuerySet method — simply append count() to the end of the appropriate QuerySet. Generate an aggregate over the QuerySet — Aggregation is when you "retrieve values that are derived by summarizing or aggregating a collection of objects." Ref: Django Aggregation Documentation.

How does Django count QuerySet?

Solution. Create your QuerySet by querying the Model as you are used to. Then simply append a . count() to your chain and you receive the number.


2 Answers

Try this code:

Message_me = Messages.objects.filter(username='myname', status=0).count() 
like image 71
Mikhail Chernykh Avatar answered Sep 28 '22 04:09

Mikhail Chernykh


You can either use Python's len() or use the count() method on any queryset depending on your requirements. Also note, using len() will evaluate the queryset so it's always feasible to use the provided count() method.

It can be used as follows:

message_count = models.Messages.objects.filter(username='username', status=0).count() 

Alternatively, (if you do not worry about performance) you can also use len():

message_count = len(models.Messages.objects.filter(username='username', status=0)) 

You should also go through the QuerySet API Documentation for more information.

like image 41
Amyth Avatar answered Sep 28 '22 05:09

Amyth