Opened 13 years ago

Last modified 13 years ago

#17167 closed Bug

ModelForm model=class not honoring reference fields with secondary database — at Initial Version

Reported by: furbeenator@… Owned by: nobody
Component: Forms Version: 1.3
Severity: Normal Keywords: ModelForm, using(), foreign key, reference field
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

When using a separate database for objects used as an instance in a ModelForm, reference fields are not searching the secondary database. For example, a secondary database (not default) is created, and set up in settings.py as database 'my_employee'. Two tables are created. One for employees, and one for departments they work in.

The tables contain these rows:

employee
username | department_id
'mark' | 1

department
department_id | name
1 | 'Dept1'
2 | 'Dept2'

The models are as follows:

class Department(models.Model):

name = models.CharField(max_length=32)
def unicode(self):

return self.name

class Employee(models.Model):

username = models.CharField(max_length=32)
department = models.ForeignKey(Department)
def unicode(self):

return self.username + ": <dept: " + self.department.name + ">"

class EmployeeForm(ModelForm):

class Meta:

model = Employee

In a view:
emp = Employee.objects.using('my_employee').get(id=1)

print emp
'mark <dept: Dept1>'

frm = EmployeeForm(instance=emp)

print frm

This generates a DatabaseError Exception, relation 'department' does not exist. It exists in the secondary database, but not in the default database.

If I create a department table in the default database, the Employee object still gets retrieved, including the id for the Department, but the department details are retrieved from the default database instead of the secondary. As follows:

In default database:
department
department_id | name
1 | 'DefaultDBDept1'
2 | 'DefaultDBDept2'

No employee table exists in default database. The view below:

emp = Employee.objects.using('my_employee').get(id=1)

print emp
'mark <dept: Dept1>'

frm = EmployeeForm(instance=emp)

print frm

This generates a form as normal, but the Department details from the default database are included instead of details from the secondary database. So, two select options are created with the labels 'DefaultDBDept1' and 'DefaultDBDept2' and the selected one is correctly 'DefaultDBDept1.' If I update the secondary table so that employee 'mark' has department_id 2, the selected option is 'DefaultDBDept2.' If I remove the default department table, the DatabaseError exception, relation 'department' does not exist, returns.

Change History (0)

Note: See TracTickets for help on using tickets.
Back to Top