---
slug: "django-multiple-database-foreignkey"
title: "Creating a ForeignKey Across Databases in Django 2.0"
description: "※ This does not mean creating constraints in an RDB. It simply means creating a ForeignKey field that works for now."
url: "https://www.ytyng.com/en/blog/django-multiple-database-foreignkey"
publish_date: "2018-05-15T03:24:56Z"
created: "2018-05-15T03:24:56Z"
updated: "2026-02-27T05:38:55.349Z"
categories: ["Django"]
keywords: ""
featured_image_url: "https://media.ytyng.com/resize/20230812/4294209815914e9a99562ba3d51bfdc5.png.webp?width=768"
has_video: false
has_music: false
video_urls: []
music_urls: []
lang: "en"
---

# Creating a ForeignKey Across Databases in Django 2.0

<p>※ This does not mean creating constraints in an RDB. It simply means creating a ForeignKey field that works for now.</p>
<p></p>
<p>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:</p>
<pre class="exception_value">Cannot assign "&lt;YourModel&gt;": the current database router prevents this relation.</pre>
<p>This error prevents saving.</p>
<p></p>
<p>In such cases, you can return True in the allow_relation method of the database router:</p>
<pre><span>def </span>allow_relation(<span>self</span>, <span>obj1</span>, <span>obj2</span>):<br />    <span>if {obj1._meta.app_label, obj2._meta.app_label} \<br /></span><span>            == {'my_app_1', 'my_app_2'}:<br /></span><span>        return True<br /></span><span></span>&uarr; This might work if you set everything to True, but if you want to judge by app_label, it would look something like this.<br />The default is None</pre>
<p>https://docs.djangoproject.com/en/2.0/topics/db/multi-db/#allow_relation</p>
<p></p>
<p>For the model that uses the ForeignKey:</p>
<pre>related_model = models.ForeignKey(<br />    YourModel, <span>on_delete</span>=models.DO_NOTHING,<br />    <span>db_constraint</span>=<span>False</span>, <span>null</span>=<span>True</span>, <span>blank</span>=<span>True</span>)</pre>
<p>If you set db_constraint=False like this (otherwise, you cannot migrate),</p>
<p>it will work as a ForeignKey.</p>
<p>However, as indicated in the code, there will be no constraints on the DB.</p>
<p></p>
