Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django queryset: Exclude list of emails using endswith

I'm running metrics on user data and want exclude users that have bogus emails like '@example.com' or '@test.com'.

I tried

emails_to_exclude = ['@example.com', '@test.com', '@mailinator.com' ....]
Users.objects.exclude(email__endswith__in=emails_to_exclude)

Unfortunately this doesn't work. Looks like endswith and in don't play nice with each other. Any ideas?

like image 614
Alexandre Avatar asked May 26 '12 19:05

Alexandre


2 Answers

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()
like image 124
Ahsan Avatar answered Sep 28 '22 05:09

Ahsan


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.

like image 22
Zubair Afzal Avatar answered Sep 28 '22 04:09

Zubair Afzal