﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
17167	ModelForm model=class not honoring reference fields with secondary database	furbeenator@…	nobody	"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:
{{{
#!python
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:
{{{
#!python
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:

{{{
#!python
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."	Bug	closed	Forms	1.3	Normal	invalid	ModelForm, using(), foreign key, reference field		Unreviewed	0	0	0	0	0	0
