Django - how do I update the database with an expression of a field?

38 Views Asked by At

We are using Django for our website, and I want to remove personal information from one of the databases. For example I want to change email addresses to their id + "@example.com". I can do it with Python:

for e in UserEmailAddress.objects.all():
    e.email="{}@example.com".format(e.id)
    e.save()

But it takes a long time if I have many users. Is there a way to do it with UserEmailAddress.objects.all().update(...) with one command that will do the same thing? I tried to use the F class but it didn't work, I probably didn't use it correctly.

I also want to filter and exclude by these expressions - for example, query all users except users where their e.email=="{}@example.com".format(e.id). I tried both queries:

from django.db.models import F

el = UserEmailAddress.objects.all().filter(email="{}@example.com".format(F('id')))
print(len(el))

el = UserEmailAddress.objects.all().exclude(email="{}@example.com".format(F('id')))
print(len(el))

Both of them return incorrect results (not what I expected).

1

There are 1 best solutions below

0
Uri On

OK, thanks to Nick I found a solution:

from django.db.models import Value
from django.db.models.functions import Concat

UserEmailAddress.objects.all().update(email=Concat('id', Value('@example.com')))

el = UserEmailAddress.objects.all().filter(email=Concat('id', Value('@example.com')))
print(len(el))

el = UserEmailAddress.objects.all().exclude(email=Concat('id', Value('@example.com')))
print(len(el))

Reference: Django: Using an F expression for a text field in an update call