﻿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
14059	ForeignKey Field validates using the default database rather than the current model instance's database	pseidel@…	nobody	"
When using multiple databases, ForeignKey fields can be setup to pull their options from a specific database.
ForeignKey.formfield({ 'using' : 'NotDefault' }).
However when validating the form, the ForeignKey fields do not validate using the associated database.

Current form validation method incorrectly validates ForeignKey relationships using the default manager instead of the model instances' database.

Django 1.2 Code: django.db.models.fields.related.py
{{{
class ForeignKey(RelatedField, Field):

    def validate(self, value, model_instance):
        if self.rel.parent_link:
            return
        super(ForeignKey, self).validate(value, model_instance)
        if value is None:
            return

        qs = self.rel.to._default_manager.filter(**{self.rel.field_name:value})
        qs = qs.complex_filter(self.rel.limit_choices_to)
        if not qs.exists():
            raise exceptions.ValidationError(self.error_messages['invalid'] % {
                'model': self.rel.to._meta.verbose_name, 'pk': value})
}}}

Proposed change will using the model_instances' database instance of the default manager.
As you can see '''self.rel.to._default_manager''' becomes '''self.rel.to._default_manager.using(model_instance._state.db)'''.
{{{

    def validate(self, value, model_instance):
        if self.rel.parent_link:
            return
        super(ForeignKey, self).validate(value, model_instance)
        if value is None:
            return

        qs = self.rel.to._default_manager.using(model_instance._state.db).filter(**{self.rel.field_name:value})
        qs = qs.complex_filter(self.rel.limit_choices_to)
        if not qs.exists():
            raise exceptions.ValidationError(self.error_messages['invalid'] % {
                'model': self.rel.to._meta.verbose_name, 'pk': value})
}}}"		closed	Forms	1.2		duplicate	multipledatabases		Unreviewed	1	0	0	0	0	0
