我们的网站使用 Django,我想从其中一个数据库中删除个人信息。例如,我想将电子邮件地址更改为他们的
id
+ "@example.com"
。我可以用Python来做:
for e in UserEmailAddress.objects.all():
e.email="{}@example.com".format(e.id)
e.save()
但是如果我有很多用户,则需要很长时间。有没有一种方法可以用
UserEmailAddress.objects.all().update(...)
用一个命令来完成同样的事情?我尝试使用 F
类,但它不起作用,我可能没有正确使用它。
我还想通过这些表达式进行过滤和排除 - 例如,查询除
e.email=="{}@example.com".format(e.id)
所在位置的用户之外的所有用户。我尝试了两个查询:
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))
它们都返回错误的结果(不是我所期望的)。
好的,感谢尼克,我找到了解决方案:
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))