I am building a separate Django project to handle a chat system, I already have a different Django project for everything else (user login info and serves API that does not relate to chat).
In this chat project, it has a model
class ChatRoom(models.Model):
rmid = models.BigAutoField(primary_key=True)
name = models.CharField(max_length=256)
people = models.ManyToManyField(to=User, blank=True)
timestamp = models.DateTimeField(auto_now_add=True)
And a database router:
class UserAuthRouter:
def db_for_read(self, model, **hints):
if model._meta.app_label == 'auth':
return 'database_with_django_auth_models'
return None
def db_for_write(self, model, **hints):
if model._meta.app_label == 'auth':
return 'database_with_django_auth_models'
return None
This allows me to use the same user login info from the main project since I have connected the database in settings.
When I try to access ChatRoom model, I believe because the many-to-many field is relating to User model in the Auth lib/module, it causes this error as it is routed to use the other database:
Django.db.utils.ProgrammingError: (1146,
"Table 'database_with_django_auth_models.apps_chat_chatroom_people' doesn't exist")
But the apps_chat_chatroom_people datatable is in the database that contains the ChatRoom schema, (i.e. the second database that is going to be used for the chat system)
What is the proper way to handle this? I want to be able to use the same login credentials.
Django doesn't support that feature cross-database-relations.
You can't use model relationships with models from different databases, you only can save the id or IDs and create your own code for obtain the data from another database.