Dynamic Model Creation for Multiple Tables in Django
For a database holding numerous temporary tables with shared schemas and dynamic names, integrating Django presents challenges. However, it is possible to use a factory function to create models with dynamic database tables.
Dynamic Database Table Management
The factory function returns a model with a specified database table. This allows dynamic data binding based on table names:
def getModel(db_table):
class MyClass(models.Model):
# Model definition goes here...
class Meta:
db_table = db_table
return MyClass
You can then instantiate the model with the specific table name:
newClass = getModel('29345794_table')
newClass.objects.filter(...)
Metaclass for Dynamic Class Naming
Since Django caches the class's _meta attribute, a metaclass is necessary to modify the class name at 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
Additional Considerations
Although initially thought to be immutable, the database table can be set dynamically:
MyModel._meta.db_table = '10293847_table'
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3