1π
β
To create a class dynamically you can use the three argument form of type
. To also dynamically create a variable or module member with the same name you can use globals()
to create variables dynamically
globals()['className'] = type('className', (object,), {'foo': 'bar'})
To create a model dynamically may be slightly more complex but you can use an abstract base class to define all the fields/methods on for convenience
class Base(models.Model):
foo = models.CharField(max_length=100)
class Meta:
abstract = True
globals()['className'] = type('className', (Base, ), {'__module__': Base.__module__})
π€Iain Shelvington
Source:stackexchange.com