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

笑着哭i 提交于 2020-04-06 02:10:07

问题


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')

回答1:


Try this code:

Message_me = Messages.objects.filter(username='myname', status=0).count()



回答2:


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.




回答3:


To get the count of you can use the Model

// In models.py
class A(models.Model):
    name = models.CharField(max_length=200)

// In views.py
from .models import A
def index(View):
    c = A.objects.filter(username='myname', status=0).count()
    print c // This will give you the count of the rows


来源:https://stackoverflow.com/questions/15635790/how-to-count-the-number-of-rows-in-a-database-table-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!