> You can't do this with a router; as you've noted, the router doesn't
> have any information about the request in which it is being used.
>
> However, you could do it by manually requesting your database
> connection whenever you use the database. For example:
>
> Author.objects.using('otherdb').filter(...)
>
> will perform a query that is guaranteed to operate on the 'otherdb',
> regardless of what the router says.

I was able to get this part working fine.  Since most views are based
on a reuable generic one this was pretty easy to do anyway.

Getting ModelForms (or ModelAdmin) to work with foreign keys is a
different story:  When the form/model is validated, the field value is
searched in the source table to verify the key exists. This lookup
uses the _default_manager (see code below), which isn't aware of the
request any more and always checks on the default database (unless I
can route it).  As a result I always get a validation error on the
form.

Looks like I need a patched/smarter RelatedField that is aware of the
database to look in?

Regards,

Johan



Snippet from 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})
####   ALWAYS CHECKS IN DEFAULT DATABASE
        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})

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.

Reply via email to