Иногда надо получить количество записей в моделях приложения django одной командой.
Если у вас до 10 моделей то можно конечно получить эти цифры через shell или функцией с count для всех моделей,
а если моделей сотни, а если тысячи 0_о?
а если моделей сотни, а если тысячи 0_о?
Или мы не знаем и знать не хотим названия моделей?
Для этого можно использовать вот такую функцию:
from collections import OrderedDict from django.apps import apps from django.core import serializers from django.db import DEFAULT_DB_ALIAS, router def get_models_counts(label): ''' Возвращает количество записей по моделям в приложении ''' model_count = 0 app_list = OrderedDict() try: app_label, model_label = label.split('.') try: app_config = apps.get_app_config(app_label) except LookupError as e: raise CommandError(str(e)) if app_config.models_module is None: return 'app_config.models_module is None' try: model = app_config.get_model(model_label) except LookupError: raise CommandError("Unknown model: {0}.{1}".format(app_label, model_label)) app_list_value = app_list.setdefault(app_config, []) if app_list_value is not None: if model not in app_list_value: app_list_value.append(model) except ValueError: app_label = label try: app_config = apps.get_app_config(app_label) except LookupError as e: raise CommandError(str(e)) if app_config.models_module is None: return 'app_config.models_module is None' app_list[app_config] = None for model in serializers.sort_dependencies(app_list.items()): model_count += 1 if not model._meta.proxy and router.allow_migrate_model( DEFAULT_DB_ALIAS, model ): try: items_total = model._default_manager.using( DEFAULT_DB_ALIAS ).count() print('{model}: {count}'.format(model=model, count=items_total)) except Exception as e: print('ERROR {model}: {error}'.format(model=model, error=e))
Функция возвращает результат вида:
>>> get_models_counts('blog')
<class 'blog.models.Categories'>: 8
<class 'blog.models.Posts'>: 1783
<class 'blog.models.Feedback'>: 1102
Комментарии