2015-09-07 115 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=#