2015-09-07 113 views
2

列值以下为python manage shellSQL命令来更新表

>>> User.objects.filter(email__icontains="gmail.com").values_list("email", flat=True) 
[u'[email protected]', u'[email protected]', u'[email protected]', u'[email protected]', u'[email protected]'] 
>>> 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'[email protected]', u'[email protected]', u'[email protected]', u'[email protected]', u'[email protected]'] 
>>> 

我想在PostgreSQL终端(python manage dbshell

写SQL命令代码,我怎么能上述转换的SQL命令

以下是我的尝试:

[Edited1]

通过SQL命令获取目标的电子邮件ID:

dp=# SELECT email FROM auth_user where email LIKE '%@gmail.com'; 
      email   
--------------------------- 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
(5 rows) 

dp=# 

回答

1

所以你要替换的电子邮件域,这里的测试选择:

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'; 
+0

@谢谢你,增加投票。我也添加我的答案,你可以检查我的答案吗? –

3

我如何在SQL命令上述转换?

你可以看看查询Django的产生对于这一点,它可能不是可执行的,在(由Django的发送如缺少PARAMS),但它会给你的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" 
+0

谢谢,最后投票。我也加了我的答案,你可以通过回答来回顾吗? –

0

以下是我的解决方案:

UPDATE auth_user Set email = replace(email, '@gmail.com', '@custom.com') where email LIKE '%@gmail.com'; 

演示:

进入dbshel​​l 1. CD的/ var/OP/PROJECT_NAME python manage dbshell

dp=# SELECT email FROM auth_user where email LIKE '%@gmail.com'; 
      email   
--------------------------- 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
(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    
---------------------------- 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
(5 rows) 

dp=#