Allow for assignment to submissions filtered by having an attachment
[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         )
20
21     def handle(self, *args, **options):
22         how_many = int(args[0])
23         examiner_names = args[1:]
24
25
26         users = User.objects.filter(username__in = examiner_names)
27         submissions_query = Submission.objects.annotate(examiners_count = Count('examiners'))
28
29         submissions = submissions_query \
30             .filter(examiners_count__lt=2).exclude(answers = None)
31         
32         if options['attachments_only']:
33             with_attachment_ids = Attachment.objects.values_list('submission_id', flat=True).all()
34             submissions = submissions.filter(id__in = with_attachment_ids)
35
36         for submission in submissions[0:how_many]:
37             submission.examiners.add(*users)
38             submission.save()
39             self.stdout.write('added to %s:%s' % (submission.id, submission.email))
40
41         count_by_examiners = dict()
42         for submission in submissions_query.all():
43             count_by_examiners[submission.examiners_count] = \
44                 count_by_examiners.get(submission.examiners_count, 0) + 1
45         self.stdout.write('%s' % count_by_examiners)