python - Single Django model, multiple tables? -
i have several temporary tables in mysql database share same schema , have dynamic names. how use django interface tables? can single model draw data multiple tables?
you could, believe, make factory function return model dynamic db_table.
def getmodel(db_table): class myclass(models.model): # define usual ... class meta: db_table = db_table return myclass newclass = getmodel('29345794_table') newclass.objects.filter( ...
edit: django not create new instance of class's _meta
attribute each time function called. creating new instance _meta
dependent upon name of class (django must cache somewhere). metaclass can used change name of class @ runtime:
def getmodel(db_table): class myclassmetaclass(models.base.modelbase): def __new__(cls, name, bases, attrs): name += db_table return models.base.modelbase.__new__(cls, name, bases, attrs) class myclass(models.model): __metaclass__ = myclassmetaclass class meta: db_table = db_table return myclass
not sure if can set dynamically on already-defined class. haven't done myself might work.
you can set whenever.
>>> mymodel._meta.db_table = '10293847_table' >>> mymodel.objects.all()
Comments
Post a Comment