LScarpinati icon

Dynamic class creation in Django

LScarpinati | PRO | 08/05/15 10:26:43 AM UTC | 0 ⭐ | 157 👁️ | Never ⏰ | []
Python |

600 B

|

None

|

0 👍

/

0 👎

# Tested from de django shell
 
In [1]: import <your app name>
In [2]: import <your app name>.models
In [3]: from django.db import models
 
In [4]: class Foo(models.Model):
   ...:     name = "Baz"
   ...:     class Meta:
   ...:         app_label = "<your app name>.models"
 
In [5]: Foo
Out[5]: __main__.Foo
 
In [6]: attrs = {
   ...: 'name':'Qux',
   ...: 'descr':'Baz',
   ...: '__module__':'<your app name>.models'}
 
In [7]: AnotherFoo = type("Foo",(models.base.ModelBase,),attrs) #Use models.base.ModelBase instead of models.Model
 
In [8]: AnotherFoo
Out[8]: <your app name>.models.Foo

Comments