Cross-Database Limitations with Django Foreign Keys
In Django, while it's possible to use different databases for various models, cross-database relationships are restricted. This means that foreign key relationships cannot span different databases when using a router to partition models.
Consider the example provided:
<code class="python">class LinkModel(models.Model): # in 'urls' database ... class NewsModel(models.Model): # in default database ... link = models.ForeignKey(LinkModel) ...</code>
In this scenario, an error will arise when attempting to assign a LinkModel instance from the urls database to the NewsModel's link field:
<code class="python">newsItem, created = NewsModel.objects.get_or_create( title="test" ) link = LinkModel.objects.using('urls').get( id=1 ) newsItem.link = link # error!</code>
Django Limitations
Django's current limitations prevent cross-database foreign key and many-to-many relationships. This is because any such relationships must be defined within a single database when using database partitioning.
Troubleshoot and Solution
There's a known issue with the Django ForeignKey() class, specifically in its validate() method. This issue exists in versions 1.2, 1.3, and 1.4rc1.
A patch is available to resolve this issue. Applying the patch should устранить the error and allow you to assign LinkModel instances from different databases to NewsModel's link field.
The above is the detailed content of Can Django Foreign Keys Span Different Databases?. For more information, please follow other related articles on the PHP Chinese website!