[melbourne-pug] Specify the database for a Django ModelForm instance

Ben Finney ben+python at benfinney.id.au
Tue Aug 9 00:29:49 EDT 2016


Anthony Briggs <anthony.briggs at gmail.com> writes:

> Right, so you can override the ModelForm's save() method, but you lose
> all of the other nice Django things, like model init, checking, etc.
> which you'll also have to recreate manually.

Yes, exactly. All I need is to tell the ModelForm which database it
should specify when interacting with the Model.

> Or you can do it the Right Way(tm) and write a custom database router

I appreciate the advice, but no, a database router is *not* right for
this. Specifying the database routing policy in a configuration file is
no use to me; the database is not known at configuration time, and I'm
not talking about multiple simultaneously-connected databases. That is
not the use case.

Rather, I'm wanting to specify *exactly one* database at *run-time*, and
have the operation use *that* database only (or fail if it can't). The
configured multi-database routing is no use for that.


The ‘ModelManager.db_router’ feature almost does the trick
<URL:https://docs.djangoproject.com/en/1.10/topics/db/multi-db/#using-managers-with-multiple-databases>,
letting me specify which database the manager will talk to. If I can
create a Model instance using that, the ModelForm will use it correctly,
I think.

But that gets the order wrong; I don't have the right field values for
instantiating the Model, and so it will fail. That's what the ModelForm
is doing to begin with: validating the fields, transforming them, and
creating the Model instance for me.

So I still need to have the ModelForm connect to the database I specify
at run-time.

-- 
 \           “People are very open-minded about new things, as long as |
  `\         they're exactly like the old ones.” —Charles F. Kettering |
_o__)                                                                  |
Ben Finney



More information about the melbourne-pug mailing list