Posted under » Django on 3 June 2023
There are times when you want to use multiple databases. Whether it is from a different MySQL database or postgres or Sqlites
DATABASES = { "default": { "NAME": "app_data", "ENGINE": "django.db.backends.postgresql", "USER": "postgres_user", "PASSWORD": "s3krit", }, "users": { "NAME": "user_data", "ENGINE": "django.db.backends.mysql", "USER": "mysql_user", "PASSWORD": "priv4te", }, }
The model would look like this.
class PostingsNote(models.Model): title = models.CharField(max_length=200) content = models.TextField() class Meta: managed = False db_table = 'postings_note'
If managed = False, no database table creation, modification, or deletion operations will be performed for this model. This is useful if the model represents an existing table or a database view that has been created by some other means. This is the only difference when managed=False. All other aspects of model handling are the same.
The views
from .models import PostingsNote ... queryset = PostingsNote.objects.using('users').all() ...
You can select the database for a QuerySet at any point in the QuerySet “chain.”
Call using() on the QuerySet to get another QuerySet that uses the specified database.
using() takes a single argument: the alias of the database on which you want to run the query.