6

Django's ORM supports querying from a specific database (when multiple are defined in your project) via the .using() function for filter-based operations.

e.g. MyModel.objects.filter(name='Bob').using('my_non_default_database')

How would you do the equivalent when creating new records, via the class MyModel() or shortcut like get_or_create()?

2 Answers 2

10

using is a method on the MyModel.objects manager, so you can do

MyModel.objects.using('my_non_default_database').get_or_create(name="Bob") 

If you have a MyModel instance, you can use the using keyword to specify the database to save to. The django docs point out some gotchas.

my_model = MyModel(name="Bob") my_model.save(using='my_non_default_database') 
Sign up to request clarification or add additional context in comments.

2 Comments

How is it handled for regular model creation? e.g. MyModel(name='bob')
Saving has a keyword argument using. I've updated my answer.
4

using is just part of the standard query chain. So, you can use it anywhere before the query is sent to the DB. get_or_create, unlike filter, is atomic: when you call it, it does it's thing immediately, so you just need to call using before that.

MyModel.objects.using('my_non_default_database').get_or_create(name='Bob') 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.