Reputation: 32347
How can I specify which database (by its alias name) a Django ModelForm should use?
A Django ModelForm knows its corresponding model, and the fields included.
The ModelForm
instance clearly knows how to specify a database, internally. It can validate its fields against the database, and can save a new model instance to the database. This implies its operations have knowledge of which database to use.
I can't find how to specify any database other than the default, when creating the ModelForm
nor when it interacts with the database::
import csv
from cumquat_app.forms import CumquatImportForm
db_alias = 'foo'
reader = csv.DictReader(input_file)
for row in reader:
fields = make_fields_from_input_row(reader)
# Wanted: ‘form = CumquatInputForm(fields, using=db_alias)’.
form = CumquatImportForm(fields)
# Wanted: ‘if form.is_valid(using=db_alias)’.
if form.is_valid():
# Wanted: ‘form.save(using=db_alias)’.
form.save()
What I need is to specify the database alias as an external user of the ModelForm
, when creating the instance or when calling ModelForm.clean
or ModelForm.is_valid
or ModelForm.save
etc.
The same way I can with the ‘using’ hook of QuerySet.using('foo')
,
or Model.save(using='foo')
.
Note that this is not a job for multi-database routing policy configuration. The use case is that I need to specify exactly one database, only known at run time. If the connection fails it should not fall back to any other, so database routes are the wrong hammer for this nail.
I can request the ModelForm.save
method to not commit its change (with commit=False
) and then use the Model.save
directly. That does not address the other behaviour of a ModelForm
which accesses the database, so it is not a solution to this question.
A ModelManager.db_manager
could do the job, if I use it to create the model instance. But I'm relying on the form to create the instance; I can't create a model instance because I don't have field values to assign yet. That's the job of the form.
If it matters: this is in a management command, where I need to be able to specify from the command line that a particular database alias is the context for a command.
What is the equivalent for using='foo'
when instantiating a ModelForm
for the model, or calling its methods (ModelForm.clean
, ModelForm.save
, etc.)?
Upvotes: 1
Views: 153
Reputation: 32347
Unless someone can find a way to do it as requested using the ModelForm
interface, I can only conclude Django offers no way to do this with the ModelForm
API as it stands.
Upvotes: 1