Creating a ForeignKey Across Databases in Django 2.0
Django
2018-05-15 03:24 (8 years ago)

※ This does not mean creating constraints in an RDB. It simply means creating a ForeignKey field that works for now.
In Django 2.0, when you try to create a ForeignKey to a model that uses a different database, you get the following error when saving:
Cannot assign "<YourModel>": the current database router prevents this relation.
This error prevents saving.
In such cases, you can return True in the allow_relation method of the database router:
def allow_relation(self, obj1, obj2):
if {obj1._meta.app_label, obj2._meta.app_label} \
== {'my_app_1', 'my_app_2'}:
return True
↑ This might work if you set everything to True, but if you want to judge by app_label, it would look something like this.
The default is None
https://docs.djangoproject.com/en/2.0/topics/db/multi-db/#allow_relation
For the model that uses the ForeignKey:
related_model = models.ForeignKey(
YourModel, on_delete=models.DO_NOTHING,
db_constraint=False, null=True, blank=True)
If you set db_constraint=False like this (otherwise, you cannot migrate),
it will work as a ForeignKey.
However, as indicated in the code, there will be no constraints on the DB.
Please rate this article (No signup or login required)
Current rating: 4.7 (3)
Related posts
Management Command to Visualize Model Relationships
How to Unit Test a Django Model with managed = False
When Updating Django from 1.6 to 2.0, django.db.utils.InternalError: (1364, "Field 'name' doesn't have a default value") Occurs During Migration
Create a Full-Text Index in Migration Files with Django 1.7
The author runs the application development company Cyberneura.
We look forward to discussing your development needs.
We look forward to discussing your development needs.