from django.core.management import BaseCommand from django.db.models import Count from django.db.models.functions import ExtractYear from books.models import Snapshot # Query to group by creator's email, count the snapshots, and order by the count class Command(BaseCommand): def handle(self, *args, **options): snapshots_grouped = (Snapshot.objects .annotate(year=ExtractYear('created')) .values('year', 'creator__email') .annotate(count=Count('id')) .order_by('year', '-count')) # Order by year and then by count (descending) # To access the results for snapshot in snapshots_grouped: modified_email = snapshot['creator__email'].split('@')[0] + '@skillbox.ch' print(f"Year: {snapshot['year']}, Creator Email: {modified_email}, Count: {snapshot['count']}")