"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How can Django models be dynamically created for multiple tables with shared schemas and dynamic names?

How can Django models be dynamically created for multiple tables with shared schemas and dynamic names?

Published on 2024-11-04
Browse:136

How can Django models be dynamically created for multiple tables with shared schemas and dynamic names?

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'
Latest tutorial More>

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