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...
3
  • is this what you're looking for? stackoverflow.com/questions/3519143/… Commented Apr 9, 2020 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 Commented Apr 9, 2020 at 11:59
  • Did manage to save instance to specific db? Could you share your code? Commented Nov 23, 2022 at 16:05

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.