以下是python manage shell
>>> User.objects.filter(email__icontains="gmail.com").values_list("email", flat=True)
[u'abc@gmail.com', u'vivekbsable@gmail.com', u'vivek@gmail.com', u'xyz@gmail.com', u'vivekbsable@gmail.com']
>>> for ii in User.objects.filter(email__icontains="gmail.com"):
... ii.email = ii.email.replace("@gmail.com", "@custom.com")
... ii.save()
...
...
>>> User.objects.filter(email__icontains="gmail.com").values_list("email", flat=True)
[]
>>> User.objects.filter(email__icontains="@custom.com").values_list("email", flat=True)
[u'vivek@custom.com', u'xyz@custom.com', u'abc@custom.com', u'vivekbsable@custom.com', u'vivekbsable@custom.com']
>>>
我想在Postgresql终端(python manage dbshell
)
如何在 SQL命令中进行上述转换?
以下是我的尝试:
[Edited1] :
通过SQL命令获取目标电子邮件ID:
dp=# SELECT email FROM auth_user where email LIKE '%@gmail.com';
email
---------------------------
vivek@gmail.com
xyz@gmail.com
abc@gmail.com
vivekbsable@gmail.com
vivekbsable@gmail.com
(5 rows)
dp=#
答案 0 :(得分:3)
如何在SQL命令中进行上述转换?
你可以看一下Django为此生成的查询,它可能不会像在运行中那样运行(例如Django发送的缺少参数),但是它会让你很好地了解Django如何翻译它到SQL
我们的想法是打印此值:Model.objects.filter(...).values_list(...).query
query = User.objects.filter(email__icontains="@custom.com").values_list("email", flat=True).query
# Make it print it
print query
print(query) # Python 3 or with "from future import print_function"
答案 1 :(得分:1)
所以你想在电子邮件中替换域,这里是test select:
select email, replace(email, '@gmail.com', '@custom.com') as new_email
from auth_user
where email like '%@gmail.com';
更新将是:
update auth_user
set email = replace(email, '@gmail.com', '@custom.com')
where email like '%@gmail.com';
答案 2 :(得分:0)
以下是我的解决方案:
UPDATE auth_user Set email = replace(email, '@gmail.com', '@custom.com') where email LIKE '%@gmail.com';
<强>演示:强>
进入dbshell
1. cd / var / op / project_name
python manage dbshell
dp=# SELECT email FROM auth_user where email LIKE '%@gmail.com';
email
---------------------------
vivek@gmail.com
xyz@gmail.com
abc@gmail.com
vivekbsable@gmail.com
vivekbsable@gmail.com
(5 rows)
dp=# SELECT email FROM auth_user where email LIKE '%@custom.com';
email
-------
(0 rows)
dp=# UPDATE auth_user Set email = replace(email, '@gmail.com', '@custom.com') where email LIKE '%@gmail.com';
UPDATE 5
dp=# SELECT email FROM auth_user where email LIKE '%@gmail.com';
email
-------
(0 rows)
dp=# SELECT email FROM auth_user where email LIKE '%@custom.com';
email
----------------------------
vivek@custom.com
xyz@custom.com
abc@custom.com
vivekbsable@custom.com
vivekbsable@custom.com
(5 rows)
dp=#