[Solved]-What is the value of self._db by default in Django?

34👍

Django default managers use using parameter to define which database underlying the manager should use for operation. This will optionally use. This is used in case you have multiple databases by which you define which database you need to use for operation.

An example user.save(using=self._db) usually defined as “default” from your database configuration in settings.py. For more info click here

Behind the scene self._db set as None. If user.save(using=None), then it will use default database.

For example, your database configuration is like

DATABASES = {
    'default': {
        'NAME': 'app_data',
        'ENGINE': 'django.db.backends.postgresql',
        'USER': 'postgres_user',
        'PASSWORD': '****'
    },
    'new_users': {
        'NAME': 'user_data',
        'ENGINE': 'django.db.backends.mysql',
        'USER': 'mysql_user',
        'PASSWORD': '****'
    }
}

Then if you want to use default database then use user.save(using=self._db)
If you want to use new_users database then use user.save(using="new_users")

1👍

Yes, Its default value is specified in settings.py

as

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'mydatabase',
'USER': 'mydatabaseuser',
'PASSWORD': 'mypassword',
'HOST': '127.0.0.1',
'PORT': '5432',
}
}

as mentioned here

0👍

Django default managers use using parameters to define which database underlying the manager should use for operation. This will optionally use. This is used in case you have multiple databases by which you define which database you need to use for operation.

An example user.save(using=self._db) is usually defined as "default" from your database configuration in settings.py.

Behind-the-scene self._db set as None. If user.save(using=None), then it will use the default database.

For example, your database configuration is like

DATABASES = {
    'default': {
        'NAME': 'app_data',
        'ENGINE': 'django.db.backends.postgresql',
        'USER': 'postgres_user',
        'PASSWORD': '****'
    },
    'new_users': {
        'NAME': 'user_data',
        'ENGINE': 'django.db.backends.mysql',
        'USER': 'mysql_user',
        'PASSWORD': '****'
    }
}

Then if you want to use default database then use user.save(using=self._db) If you want to use new_users database then use user.save(using="new_users")

Leave a comment