Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Django ORM get_or_create with multiple databases

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()?

like image 798
Cerin Avatar asked Nov 02 '11 16:11

Cerin


People also ask

Can Django support multiple databases?

Django's admin doesn't have any explicit support for multiple databases. If you want to provide an admin interface for a model on a database other than that specified by your router chain, you'll need to write custom ModelAdmin classes that will direct the admin to use a specific database for content.

How does Django save multiple data?

To create multiple records based on a Django model you can use the built-in bulk_create() method. The advantage of the bulk_create() method is that it creates all entries in a single query, so it's very efficient if you have a list of a dozen or a hundred entries you wish to create.


2 Answers

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')
like image 59
Alasdair Avatar answered Oct 13 '22 02:10

Alasdair


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')
like image 43
Chris Pratt Avatar answered Oct 13 '22 02:10

Chris Pratt