Using Django ORM get_or_create with multiple databases

Django ORM supports queries from a specific database (when several of them are defined in your project) using the .using () function for filter-based operations.

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

How will you do the equivalent when creating new entries through the MyModel () class or shortcut, for example get_or_create ()?

+6
source share
2 answers

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

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

If you have an instance of MyModel, you can use the using keyword to specify the database to save. django docs indicate some errors.

 my_model = MyModel(name="Bob") my_model.save(using='my_non_default_database') 
+10
source

using is part of the standard query chain. Thus, you can use it anywhere before sending a request to the database. get_or_create , unlike filter , is atomic: when you call it, it does it right away, so you just need to call using before.

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

Source: https://habr.com/ru/post/900626/


All Articles