5

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)
Bigbob556677
  • 1,805
  • 1
  • 13
  • 38

1 Answers1

10

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))
Dash Winterson
  • 1,197
  • 8
  • 19