Reputation: 2158
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)
Upvotes: 7
Views: 3821
Reputation: 1295
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))
Upvotes: 15