Improved Multiple Model Files

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# myapp/
#   models/
#     __init__.py
#     models1.py
#     models2.py

############# __init__.py #############
import django.db.models        
import sys                     

appname = "myapp"
from models1 import *
from models2 import *

__all__ = []                   

for decl in globals().values(): 
  try:
    if decl.__module__.startswith(__name__) and issubclass(decl, django.db.models.Model):
      decl._meta.db_table = decl._meta.db_table.replace('models', appname)
      decl._meta.app_label = appname   
      __all__.append(decl.__name__)
      django.db.models.loading.register_models(appname, decl)
  except:
    pass

More like this

  1. more on manager methods by grahamu 7 years, 1 month ago
  2. Multiple Delete in Admin by gfranxman 6 years, 1 month ago
  3. Non model specific CSV export of database content by sethtrain 6 years, 2 months ago
  4. Custom 'save' method, automate creating pdf file from entry. by I159 2 years, 6 months ago
  5. Multiple Choice model field by danielroseman 5 years, 5 months ago

Comments

kekomal (on January 17, 2014):

Thanks, very useful.

One improvement: Instead of...

if decl.__module__.startswith(__name__) and issubclass(decl, django.db.models.Model):

...use...

if decl.__module__.startswith(__name__) and issubclass(decl, django.db.models.Model) and not decl._meta.abstract:

...so that parent model abstract classes are not unnecessarily mapped to DB.

#

(Forgotten your password?)