bignose
bignose

Reputation: 32347

Use a specific database with a ModelForm

How can I specify the database to use when a ModelForm saves its data?

The multiple-database support in Django means that I can define more databases than just the default. For example:

# settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': ':memory:',
    },
    },
    'staging': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'HOST': 'db.example.com',
        # …
    },
}

This allows a model manager to query a different database from the default:

from django import models

class Foo(models.Model):
    # …

queryset = Foo.objects.using('staging').all()

A ModelForm subclass also interacts with the database:

from django import forms

from .models import Foo

class FooImportForm(forms.ModelForm):
    class Meta:
        model = Foo
        fields = [
            # …
        ]

fields = {
    # …
}
form = FooImportForm(fields)
form.save()

How can I specify that the FooModelForm instance should use the staging database when I form.save()? I can't see a place where to specify the equivalent of using('staging').

Upvotes: 0

Views: 612

Answers (2)

bignose
bignose

Reputation: 32347

The Model.save method accepts the using parameter to specify the database:

foo = Foo(fields)
foo.save(using='staging')

The ModelForm.save method returns the Model instance:

foo_form = FooImportForm(fields)
foo = foo_form.save()

The ModelForm.save method can optionally be told not to commit:

foo_form.save(commit=False)

Putting it all together:

foo_form = FooImportForm(fields)
foo = foo_form.save(commit=False)
foo.save(using='staging')

Upvotes: 0

Raja Simon
Raja Simon

Reputation: 10315

Whatever form do not commit first then now you get the model object and save it using

f = form.save(commit=False)
f.save(using='staging')

Upvotes: 3

Related Questions