0

I have a set up with multiple databases: let's call them db1, db2 and db3. db1 is default.

I now have a ModelForm that is meant to save an object Customer to db2.

class CustomerCreateForm(ModelForm):
    class Meta:
        model = Customer
        fields = ["name", "type"]

My view:

if "create" in request.POST:
    f = CustomerCreateForm(data=request.POST)
    customer = f.save(commit=False)  # Error -> no table 'customer' on database 'db1'
    customer.date_joined = datetime.now()
    customer.save(using='db2')

It appears that the save() method does not have a using argument. How can I save an instance of Customer to db2 using a ModelForm? Of course I can always use a simple Form instead but I wanted to see if there is a correct way of doing this via ModelForm?

EDIT: This issue also appears when checking if the form is valid.

f = CustomerCreateForm(data=request.POST)
if f.is_valid(): # Error: No model Customer on database db1
    # some more code...
michal111
  • 400
  • 4
  • 18
  • is this what you're looking for? https://stackoverflow.com/questions/3519143/django-how-to-specify-a-database-for-a-model – Chris Curvey Apr 09 '20 at 11:41
  • no, my database routers are set up correctly. calling `modelinstance.save(using=db2)` works fine for me. however, you cannot use the `using` argument when saving a model instance from a `ModelForm`. i.e. `f.save(commit=False, using='db2')` - unexpected argument `using` – michal111 Apr 09 '20 at 11:59
  • Did manage to save instance to specific db? Could you share your code? – data_b77 Nov 23 '22 at 16:05

0 Answers0