code style
[edumed.git] / wtem / management / commands / wtem_assign_submissions.py
1 # -*- coding: utf-8 -*-
2 from optparse import make_option
3
4 from django.core.management.base import BaseCommand
5 from django.db.models import Count
6 from django.contrib.auth.models import User
7
8 from wtem.models import Submission, Attachment
9
10
11 class Command(BaseCommand):
12
13     option_list = BaseCommand.option_list + (
14         make_option(
15             '--with-attachments-only',
16             action='store_true',
17             dest='attachments_only',
18             default=False,
19             help='Take into account only submissions with attachments'),
20         make_option(
21             '--without-attachments-only',
22             action='store_true',
23             dest='no_attachments_only',
24             default=False,
25             help='Take into account only submissions without attachments'),
26         )
27
28     def handle(self, *args, **options):
29
30         limit_from = int(args[0])
31         limit_to = int(args[1])
32         examiner_names = args[2:]
33
34         users = User.objects.filter(username__in=examiner_names)
35         all_submissions = Submission.objects.annotate(examiners_count=Count('examiners'))
36
37         submissions = all_submissions.exclude(answers=None)
38
39         with_attachment_ids = Attachment.objects.values_list('submission_id', flat=True).all()
40         if options['attachments_only']:
41             submissions = submissions.filter(id__in=with_attachment_ids)
42         if options['no_attachments_only']:
43             submissions = submissions.exclude(id__in=with_attachment_ids)
44
45         for submission in submissions.order_by('id')[limit_from:limit_to]:
46             submission.examiners.add(*users)
47             submission.save()
48             self.stdout.write('added to %s:%s' % (submission.id, submission.email))
49
50         count_by_examiners = dict()
51         for submission in all_submissions.all():
52             count_by_examiners[submission.examiners_count] = \
53                 count_by_examiners.get(submission.examiners_count, 0) + 1
54         self.stdout.write('%s' % count_by_examiners)