How to work around lack of support for foreign keys across databases in Django

后端 未结 9 1376
生来不讨喜
生来不讨喜 2020-12-07 09:59

I know Django does not support foreign keys across multiple databases (originally Django 1.3 docs)

But I\'m looking for a workaround.

What doesn\'t work

9条回答
  •  太阳男子
    2020-12-07 10:02

    I have a new solution for django v1.10. There are two parts. It works with django.admin and django.rest-framework.

    1. Inherit the 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
                    )
    
    1. In field declaration, use db_constraint=False, for example,

    album=ForeignKeyAcrossDb(Singer, db_constraint=False, on_delete=models.DO_NOTHING)

提交回复
热议问题