Login

Improved Multiple Model Files

Author:
softmechanics
Posted:
December 21, 2009
Language:
Python
Version:
1.1
Tags:
model-package multiple-model-files
Score:
1 (after 1 ratings)

Most other methods I've seen for splitting an app's models across multiple files involve adding a couple lines to every model. This method factors out those duplicate lines into one place.

 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

Comments

kekomal (on January 17, 2014):
<p>Thanks, very useful.</p> <p>One improvement: Instead of...</p> <pre>if decl.__module__.startswith(__name__) and issubclass(decl, django.db.models.Model): </pre> <p>...use...</p> <pre>if decl.__module__.startswith(__name__) and issubclass(decl, django.db.models.Model) and not decl._meta.abstract: </pre> <p>...so that parent model abstract classes are not unnecessarily mapped to DB.</p>

#

Please login first before commenting.