- commit
- a5fc4466f274f6dbc49c2f0f05bd8fb7481a37ce
- parent
- 22f1edfc3c14b049c1e732f4dfdaf09d2db09f4c
- Author
- Tobias Bengfort <bengfort@mpib-berlin.mpg.de>
- Date
- 2021-11-03 11:16
add get_stats
Diffstat
| M | model_stats/views.py | 40 | ++++++++++++++++++++++++++++++++++++++++ |
1 files changed, 40 insertions, 0 deletions
diff --git a/model_stats/views.py b/model_stats/views.py
@@ -1,4 +1,44 @@ 1 1 from django.template.response import TemplateResponse -1 2 from django.contrib.contenttypes.models import ContentType -1 3 from django.contrib.contenttypes.fields import GenericForeignKey -1 4 -1 5 -1 6 def percent(part, total): -1 7 if total == 0: -1 8 return None -1 9 p = part * 100 // total -1 10 return '{}%'.format(p) -1 11 -1 12 -1 13 def get_stats(): -1 14 for ct in ContentType.objects.order_by('app_label', 'model'): -1 15 cls = ct.model_class() -1 16 if not cls: -1 17 continue -1 18 count = cls.objects.count() -1 19 -1 20 fields = [] -1 21 for field in cls._meta.get_fields(): -1 22 if isinstance(field, GenericForeignKey): -1 23 pass # FIXME -1 24 else: -1 25 try: -1 26 kwargs = {field.name: field.get_default()} -1 27 field_count = cls.objects.exclude(**kwargs).count() -1 28 except (AttributeError, ValueError): -1 29 kwargs = {field.name: None} -1 30 field_count = cls.objects.exclude(**kwargs).count() -1 31 fields.append({ -1 32 'name': field.name, -1 33 'count': field_count, -1 34 'percent': percent(field_count, count), -1 35 }) -1 36 -1 37 yield { -1 38 'name': cls.__name__, -1 39 'count': count, -1 40 'fields': fields, -1 41 } 2 42 3 43 4 44 def stats_view(request):