Thursday, May 30, 2013

Using multiple model files per app with the Improved Multiple Model Files Django Snippet

I'm trying to use multiple files for my models in a single app.
I found a nice solution on Django Snippets:
http://djangosnippets.org/snippets/1838/
but I'm not able to get it to work.
The docs assume that I know more than I do about how this solution works.
Its involves using a models folder for the app like this:
# myapp/  #   models/  #     __init__.py  #     models1.py  #     models2.py

and then including an __init__.py file in the folder to make it a package
this file also contains this code:
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  
I don't understand this code, but hopefully I don't have to.
I just want to be able to import my individual model modules:
models1.py & models2.py
from my views and admin.py
the import statements are not included in the snippet
and I've tried what seems reasonable and keep getting errors importing the modules saying they don't exist
I would expect you do something like
import myapp.models.model1
&
import myapp.models.model2
but this doesn't work.
maybe I don't understand the magic in the __init__.py file
or I'm just being plain stupid.
Can someone point me toward getting this solution working with my imports?

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

No comments:

Post a Comment