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