Django queryset: Exclude list of emails using endswith

Simply loop over the QuerySet, as QuerySets are lazy.

emails_to_exclude = ['@example.com', '@test.com', '@mailinator.com' ....]
users = Users.objects
for exclude_email in emails_to_exclude:
    users = users.exclude(email__endswith=exclude_email)
users = users.all()

You can also do this with regular expressions in single query.

emails_to_exclude = ['@example.com', '@test.com', '@mailinator.com' ....]
User.objects.exclude(email__regex = "|".join(emails_to_exclude))

I don't know the efficiency of this query.

This will not work for SQLite, as it has no built in regular expression support.


This should works with the latest version of Python and Django. The reduce function is a good friend.

from functools import reduce
from operator import or_
from django.db.models import Q

emails_to_exclude = ['@example.com', '@test.com', '@mailinator.com' ....]
users = ( Users.objects
    .exclude( reduce( or_, ( 
        Q(( "email__endswith", k ))
        for k in emails_to_exclude 
    ) ) )
)

You can probably loop over the emails and build up a Q Object. Actually, you can probably do a 1-liner if you're clever.

User.objects.exclude(bitwise_or_function[Q(email__endswith=e) for e in emails_to_exclude])

Something like that. I don't remember the function to bitwise-OR a whole list together, my Python's rusty.