I've tried using multiple database in my Django project. I create a model with foreign key to User but it can't save to second database.
This is the UserData model:
class UserData(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='user', related_query_name='user')
is_controller = models.BooleanField(default=False)
phone_number = models.CharField(max_length=255, blank=True, null=True)
Then in views:
instance = UserData(
user=request.user,
nim=nim,
phone_number=phone
)
After that, I save the instance:
>>> instance.save() #it works on default database (sqlite)
>>> instance.save(using='db_alias') # return an error
The error said it was cannot add or update child row because of the foreign key
(1452, 'Cannot add or update a child row: a foreign key constraint fails ('labs'.'presence_userdata', CONSTRAINT 'presence_userdata_user_id_4b3dfc56_fk_auth_user_id' FOREIGN KEY ('user_id') REFERENCES 'auth_user' ('id'))')`
Can anyone help me solve this problem?
Django does not support any FK or M2M relations between multiple databases. As stated in the documentation, any FK or M2M relation must happen in a single database instance.
Reference https://docs.djangoproject.com/en/4.1/topics/db/multi-db/#cross-database-relations