Creating a ForeignKey Across Databases in Django 2.0

Django
2018-05-15 12:24 (6 years ago) ytyng

※ 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.

Current rating: 4.7

Comments

Archive

2024
2023
2022
2021
2020
2019
2018
2017
2016
2015
2014
2013
2012
2011