Reputation: 261
I was reading over the docs and have my second database sync'd and ready to go. I find the section on telling django what database it should use by using the .using('database')
.
On that same line of thought I tried to show django where it should save a User once it is created like thi:
User.objects.using('user_data').create_user(username=username, password=password, email='')
When I tried that bit of code out I got this error:
AttributeError at /signup/
'QuerySet' object has no attribute 'create_user'
So I'm just curious if there is a different way I have to tell django that I want it saved in user_data and not the default db? I'd prefer not to use a router as i find them to be pretty confusing. Thanks.
Upvotes: 2
Views: 653
Reputation: 2175
.using('database')
returns a queryset, so you use this function to only get a query. In case of using create(), you have to use it via db_manager() like this:
User.objects.db_manager('database').create_user(...)
Take a look at: multi-db for more information.
Upvotes: 2
Reputation: 10119
About the error 'QuerySet' object has no attribute 'create_user'
, according to the documentation of 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.)
Emphasis mine. You need to do this:
User.objects.db_manager('new_users').create_user(username=username, password=password, email='')
Also, you can try this (haven't tested):
new_user = User()
new_user.username = username
new_user.password = password
new_user.email = ''
new_user.save(using='user_data')
More info for Selecting a database for save() in Django's documentation.
Upvotes: 5