I have several temporary tables in a MySQL database that share the same schema and have dynamic names. How would I use Django to interface with those tables? Can a single mo
Create a model for your table dynamically.
from django.db import models
from django.db.models.base import ModelBase
def create_model(db_table):
class CustomMetaClass(ModelBase):
def __new__(cls, name, bases, attrs):
model = super(CustomMetaClass, cls).__new__(cls, name, bases, attrs)
model._meta.db_table = db_table
return model
class CustomModel(models.Model):
__metaclass__ = CustomMetaClass
# define your fileds here
srno = models.IntegerField(db_column='SRNO', primary_key=True)
return CustomModel
and you can start querying the database.
In [6]: t = create_model('trial1')
In [7]: t._meta.db_table
Out[7]: 'trial1'
In [8]: t.objects.all() # default db
Out[8]: [, '(remaining elements truncated)...']
In [9]: t.objects.using('test').all() # test db
Out[9]: [, '(remaining elements truncated)...']