Login

Improved Multiple Model Files

Author:
softmechanics
Posted:
December 21, 2009
Language:
Python
Version:
1.1
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

  1. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 11 months, 3 weeks 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.

#

Please login first before commenting.