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()?
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.
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.
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')
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With