bignose
bignose

Reputation: 32347

Specify the database for a Django ModelForm instance

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').

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

Answers (1)

bignose
bignose

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

Related Questions