Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop Through Every Model In Django Project

In django, is there a way to loop through each model that is currently in your database?

I would like to be able to have a function that gets the total number of rows in all of my models, per model, without having to the function every time I added a new model.

the output being something like

model1 rows: 23

model2 rows:234

and then if I were to add a new model it would automatically output

model1 rows: 23

model2 rows:234

model3 rows:0

the ideal format would be something like.

def getDbStatus()
    for m in Models:
        print(m.objects.count)
like image 485
Bigbob556677 Avatar asked Jul 16 '26 05:07

Bigbob556677


1 Answers

Use get_models() and count()

import django.apps
for model in django.apps.apps.get_models():
    name = model.__name__
    count = model.objects.all().count()
    print("{} rows: {}".format(name, count))
like image 57
Dash Winterson Avatar answered Jul 17 '26 20:07

Dash Winterson