user2130951
user2130951

Reputation: 2741

Connect django model to different table name with same structure

I have a database where I import data from the stock market. This will all be identical tables with only the date differing. How would I connect a django model with a dynamic table name?

Upvotes: 2

Views: 1362

Answers (2)

class YourRouter:
def db_for_read(self, model, **hints):
    if model._meta.model_name == 'yourmodel':
        model._meta.db_table == 'your_new_table'
    return None

def db_for_write(self, model, **hints):
    if model._meta.model_name == 'yourmodel':
        model._meta.db_table == 'your_new_table'
    return None

def allow_relation(self, obj1, obj2, **hints):
    return False

def allow_migrate(self, db, app_label, model_name=None, **hints):
    return False

I think, it will work, but make some trouble with relations

Upvotes: 0

Nafees Anwar
Nafees Anwar

Reputation: 6608

You can use db_table option in models Meta for specifying different table name like this.

class YourModel(models.Model):
    ...

    class Meta:
        db_table = 'YOUR_TABLE_NAME'

This will work only if your table is in the same database you are using as default in django settings. However if this database if different than your default database, you have to add it in DATABASES configuration under another name and make your own database router for proper routing like this.

settings.py

DATABASES = {
    ...
    'other': {
        'NAME': 'primary',
        'ENGINE': 'django.db.backends.mysql',
        'USER': 'mysql_user',
        'PASSWORD': 'spam',
    }, 

}
DATABASE_ROUTERS = ['path.to.YourRouter']

routers.py (create it)

class YourRouter:
    def db_for_read(self, model, **hints):
        if model._meta.model_name == 'yourmodel':
            return 'other'
        return None

    def db_for_write(self, model, **hints):
        if model._meta.model_name == 'yourmodel':
            return 'other'
        return None

    def allow_relation(self, obj1, obj2, **hints):
        return False

    def allow_migrate(self, db, app_label, model_name=None, **hints):
        return False

Upvotes: 2

Related Questions