2012-04-18 77 views
0

我正在閱讀文檔並讓我的第二個數據庫同步並準備就緒。我找到了關於通過使用.using('database')來告訴django它應該使用哪個數據庫的部分。如何在非默認數據庫中創建用戶?

基於同樣的思路我試圖表明Django的,它應該保存用戶一旦像THI創建:

User.objects.using('user_data').create_user(username=username, password=password, email='') 

當我試圖代碼,有點脫離我得到這個錯誤:

AttributeError at /signup/ 

'QuerySet' object has no attribute 'create_user' 

所以我只是好奇,如果有不同的方式,我必須告訴Django,我希望它保存在user_data而不是默認數據庫?我寧願不使用路由器,因爲我發現它們相當混亂。謝謝。

回答

3

關於錯誤'QuerySet' object has no attribute 'create_user',根據Using managers with multiple databases文檔:

For example, say you have a custom manager method that touches the database -- User.objects.create_user(). Because create_user() is a manager method, not a QuerySet method, you can't do User.objects.using('new_users').create_user(). (The create_user() method is only available on User.objects, the manager, not on QuerySet objects derived from the manager.)

重點煤礦。你需要這樣做:

User.objects.db_manager('new_users').create_user(username=username, password=password, email='') 

此外,你可以試試這個(沒有測試):爲Selecting a database for save() Django的文檔中

new_user = User() 
new_user.username = username 
new_user.password = password 
new_user.email = '' 
new_user.save(using='user_data') 

更多信息。

+0

那麼我將如何去使用Authincate()?或登錄()?或註銷()我也猜。我嘗試了文檔中的三種方法,但都沒有提供所需的結果。使用:'user = authenticate(username = username,password = password,using ='user_data')'不會返回錯誤,但它也不會產生所需的效果 – city 2012-04-18 21:58:22

0

.using('database')返回一個查詢集,所以你使用這個函數只能得到一個查詢。在使用create()的情況下,必須通過db_manager()像這樣使用它:

User.objects.db_manager('database').create_user(...) 

看看:multi-db以獲取更多信息。

相關問題