1
0
Fork 0

Move the bulk get_new_mail to queryset

This commit is contained in:
George Cheng 2020-07-26 14:21:21 +08:00
parent 505bc8d1c9
commit 0c6f6aa6ce
3 changed files with 27 additions and 7 deletions

View file

@ -20,11 +20,7 @@ logger = logging.getLogger(__name__)
def get_new_mail(mailbox_admin, request, queryset): def get_new_mail(mailbox_admin, request, queryset):
count = 0 queryset.get_new_mail()
for mailbox in queryset.all():
logger.debug('Receiving mail for %s' % mailbox)
count += sum(1 for i in mailbox.get_new_mail())
logger.debug('Received %d %s.', count, 'mails' if count != 1 else 'mail')
get_new_mail.short_description = _('Get new mail') get_new_mail.short_description = _('Get new mail')

View file

@ -36,9 +36,23 @@ from django_mailbox.transports import Pop3Transport, ImapTransport, \
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
class MailboxQuerySet(models.QuerySet):
def get_new_mail(self):
count = 0
for mailbox in self.all():
logger.debug('Receiving mail for %s' % mailbox)
count += sum(1 for i in mailbox.get_new_mail())
logger.debug('Received %d %s.', count, 'mails' if count != 1 else 'mail')
class MailboxManager(models.Manager):
def get_queryset(self):
return MailboxQuerySet(self.model, using=self._db)
class ActiveMailboxManager(models.Manager): class ActiveMailboxManager(models.Manager):
def get_queryset(self): def get_queryset(self):
return super().get_queryset().filter( return MailboxQuerySet(self.model, using=self._db).filter(
active=True, active=True,
) )
@ -106,7 +120,7 @@ class Mailbox(models.Model):
null=True null=True
) )
objects = models.Manager() objects = MailboxManager()
active_mailboxes = ActiveMailboxManager() active_mailboxes = ActiveMailboxManager()
@property @property

View file

@ -34,3 +34,13 @@ class TestMailbox(TestCase):
self.assertEqual(mailbox.last_polling, None) self.assertEqual(mailbox.last_polling, None)
list(mailbox.get_new_mail()) list(mailbox.get_new_mail())
self.assertNotEqual(mailbox.last_polling, None) self.assertNotEqual(mailbox.last_polling, None)
def test_queryset_get_new_mail(self):
mailbox = Mailbox.objects.create(uri="mbox://" + os.path.join(
os.path.dirname(__file__),
'messages',
'generic_message.eml',
))
Mailbox.objects.filter(pk=mailbox.pk).get_new_mail()
mailbox.refresh_from_db()
self.assertNotEqual(mailbox.last_polling, None)