LScarpinati

Dynamic class creation in Django

Aug 5th, 2015
32
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.60 KB | None | 0 0
  1. # Tested from de django shell
  2.  
  3. In [1]: import <your app name>
  4. In [2]: import <your app name>.models
  5. In [3]: from django.db import models
  6.  
  7. In [4]: class Foo(models.Model):
  8.    ...:     name = "Baz"
  9.    ...:     class Meta:
  10.    ...:         app_label = "<your app name>.models"
  11.  
  12. In [5]: Foo
  13. Out[5]: __main__.Foo
  14.  
  15. In [6]: attrs = {
  16.    ...: 'name':'Qux',
  17.    ...: 'descr':'Baz',
  18.    ...: '__module__':'<your app name>.models'}
  19.  
  20. In [7]: AnotherFoo = type("Foo",(models.base.ModelBase,),attrs) #Use models.base.ModelBase instead of models.Model
  21.  
  22. In [8]: AnotherFoo
  23. Out[8]: <your app name>.models.Foo
Advertisement
Add Comment
Please, Sign In to add comment