Cross database foreign key is used when models in different databases needs to be related with each other. Django only have limited support for cross database foreign keys and this library is designed to extend that support.
Enable cross database relationships using Django database router (https://docs.djangoproject.com/en/2.2/topics/db/multi-db/#topics-db-multi-db-routing).
Make sure that relations are allowed between objects by enabling relations ships in allow_relation
functions of the Router.
Use CrossDBForeignKey
and CrossDBOneToOneField
to define cross database relationships.
# Department is in the 'Management' database
class Department(models.Model):
code = models.CharField(max_length=6)
# Employee is in the 'HR' database
class Employee(models.Model):
name = models.TextField()
department = CrossDBForeignKey(
Department,
on_delete=models.CASCADE,
related_name='employees',
)
- Does not support queries spanning to multiple models in different databases.
- Support only CASCADE, SET_NULL, and DO_NOTHING for on_delete.