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

Ben Finney ben+python at benfinney.id.au
Mon Aug 8 21:32:53 EDT 2016


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

> The database is normally routed via the model, rather than the form,
> so a ModelForm would generally just pick whatever the model uses.

Okay, so how do I specify the arguments the ModelForm will use when
interacting with the Model instance it creates?

I'm trying to hook into the ModelForm's validation (ModelForm.clean) and
model creation (ModelForm.save) behaviour, to tell it which database to
use for that operation.

> I would imagine that trying to hack on the form directly would be a
> Bad Plan(tm).

Sure, I'm trying to do this as an external user of the ModelForm.

> https://docs.djangoproject.com/en/1.10/topics/db/multi-db/#automatic-database-routing

I'm not interested in automatically routing all operations; I want to
*specify* which database, for a particular operation.

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.

The same way I can with the ‘using’ hook of ModelManager.using('foo'),
or Model.save(using='foo'). What is the equivalent for a ModelForm
instance?

-- 
 \         Fry: “Take that, poor people!”  Leela: “But Fry, you’re not |
  `\     rich.”  Fry: “No, but I will be someday, and then people like |
_o__)                                  me better watch out!” —Futurama |
Ben Finney



More information about the melbourne-pug mailing list