0

I have in my User Profile, one field to define the Database name, that user can connect.

DATABASES = {
    'app_data': {
        'NAME': 'app_data',
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'USER': 'postgres_user',
        'PASSWORD': 's3krit'
    },
    'DBNAME_1': {
        'NAME': 'user_data',
        'ENGINE': 'django.db.backends.mysql',
        'USER': 'mysql_user',
        'PASSWORD': 'priv4te'
    }
}

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    dbname = models.CharField(u'Database name', max_length=100, null=True, blank=True)

not connecting to 2 different database only creating in single database

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
mr.perfect
  • 11
  • 2

1 Answers1

0

You can use database of your choice with using keyword at runtime.

UserProfile.objects.using('user_data').all()
Shaheer Raza
  • 39
  • 1
  • 9
  • You can create a seperate database connection and write raw sql queries. – Shaheer Raza Aug 06 '19 at 05:11
  • how to create seperate database connection?? – mr.perfect Aug 06 '19 at 06:20
  • if you are using postgres then `conn = psycopg2.connect(host=host, database=database, user=user, password=password) cur = conn.cursor()` then write query as `sql = "select * from any_table;" ` `cursor.execute(sql)` then `data = cursor.fetchall()` – Shaheer Raza Aug 06 '19 at 07:06
  • I want to create a database dynamically at runtime in mysql or sqlite. And not by using raw sql queries. Pls suggest me? – mr.perfect Aug 06 '19 at 07:23
  • This answers you in better way https://stackoverflow.com/questions/6585373/django-multiple-and-dynamic-databases – Shaheer Raza Aug 06 '19 at 07:29