from optparse import make_option

from django.core.management.base import BaseCommand, CommandError
from django.db.models import Count
from django.contrib.auth.models import User

from contact.models import Contact
from wtem.models import Submission, Attachment


class Command(BaseCommand):

    option_list = BaseCommand.option_list + (
        make_option('--with-attachments-only',
            action='store_true',
            dest='attachments_only',
            default=False,
            help='Take into account only submissions with attachments'),
        )

    def handle(self, *args, **options):
        how_many = int(args[0])
        examiner_names = args[1:]


        users = User.objects.filter(username__in = examiner_names)
        submissions_query = Submission.objects.annotate(examiners_count = Count('examiners'))

        submissions = submissions_query \
            .filter(examiners_count__lt=2).exclude(answers = None)
        
        if options['attachments_only']:
            with_attachment_ids = Attachment.objects.values_list('submission_id', flat=True).all()
            submissions = submissions.filter(id__in = with_attachment_ids)

        for submission in submissions.order_by('id')[0:how_many]:
            submission.examiners.add(*users)
            submission.save()
            self.stdout.write('added to %s:%s' % (submission.id, submission.email))

        count_by_examiners = dict()
        for submission in submissions_query.all():
            count_by_examiners[submission.examiners_count] = \
                count_by_examiners.get(submission.examiners_count, 0) + 1
        self.stdout.write('%s' % count_by_examiners)

@@ -549,16 +549,242 @@
 ents'),%0A
+        make_option('--without-attachments-only',%0A            action='store_true',%0A            dest='no_attachments_only',%0A            default=False,%0A            help='Take into account only submissions without attachments'),%0A
         
@@ -1178,52 +1178,8 @@
    %0A
-        if options%5B'attachments_only'%5D:%0A    
     
@@ -1281,44 +1281,203 @@
     
-    submissions = submissions.filter
+if options%5B'attachments_only'%5D:%0A            submissions = submissions.filter(id__in = with_attachment_ids)%0A        if options%5B'no_attachments_only'%5D:%0A            submissions = submissions.exclude
 (id_

Allow for assignment to submissions filtered by not having an attachment