I know Django does not support foreign keys across multiple databases (originally Django 1.3 docs)
But I\'m looking for a workaround.
I have a new solution for django v1.10. There are two parts. It works with django.admin and django.rest-framework.
ForeignKey
class and create ForeignKeyAcrossDb
, and override the validate()
function, based on this ticket and this post.class ForeignKeyAcrossDb(models.ForeignKey):
def validate(self, value, model_instance):
if self.remote_field.parent_link:
return
super(models.ForeignKey, self).validate(value, model_instance)
if value is None:
return
using = router.db_for_read(self.remote_field.model, instance=model_instance)
qs = self.remote_field.model._default_manager.using(using).filter(
**{self.remote_field.field_name: value}
)
qs = qs.complex_filter(self.get_limit_choices_to())
if not qs.exists():
raise exceptions.ValidationError(
self.error_messages['invalid'],
code='invalid',
params={
'model': self.remote_field.model._meta.verbose_name, 'pk': value,
'field': self.remote_field.field_name, 'value': value,
}, # 'pk' is included for backwards compatibility
)
db_constraint=False
, for example, album=ForeignKeyAcrossDb(Singer, db_constraint=False, on_delete=models.DO_NOTHING)