Having models' declarations at two folders in Django
How can you have model declarations at two different directories in Django?
I have the model at the directory Code which contains "init.py", "models.py" and "admin.py". It is working properly alone.
I want to have the directory History which has the model of the revisions of the given questions. I have the similar files in the directory.
I need to tell Django to use the model at the directory "History" somehow, since I have a ManyToMany relation in the table Questions to the other directory.
I get the following import error
ImportError at /
cannot import name history
Request Method: GET
Request URL: http://127.0.0.1:8000/
Exception Type: ImportError
Exception Value:
cannot import name history
Exception Location: /home/noa/build/CML/../CML/codes/models.py in <module>, line 2
Python Executable: /usr/bin/python
Python Version: 2.6.2
Python Path: ['/home/noa/build/CML', '/usr/lib/python2.6', '/usr/lib/python2.6/plat-linux2', '/usr/lib/python2.6/lib-tk', '/usr/lib/python2.6/lib-old', '/usr/lib/python2.6/lib-dynload', '/usr/lib/python2.6/dist-packages', '/usr/lib/python2.6/dist-packages/PIL', '/usr/lib/python2.6/dist-packages/gst-0.10', '/var/lib/python-support/python2.6', '/usr/lib/python2.6/dist-packages/gtk-2.0', '/var/lib/python-support/python2.6/gtk-2.0', '/var/lib/python-support/python2.6/pyinotify', '/usr/lib/python2.6/dist-packages/wx-2.8-gtk2-unicode', '/usr/local/lib/python2.6/dist-packages']
Server tim开发者_开发技巧e: Fri, 11 Dec 2009 15:46:30 -0600
Since it sounds like both of your directories are Django apps, and assuming you've put both of them in your INSTALLED_APPS
list in settings.py
you can refer to them using a string without having to import:
# in code/models.py
class Questions(models.Model):
histories = models.ManyToManyField('history.MyHistoryModel')
Note that the path is case sensitive... so if you app is truly called 'History' you will need to reference it using 'History.MyHistoryModel'.
Generally people just have one "models" directory, or even sometimes just one models file. If you get to the point that you feel you need 2 full directories for your models, it's probably better to start thinking about breaking your one app, into a couple of small apps instead generally. That being said, there's a number of things that could be potentially wrong just with your setup that we can't see.
Anytime I have an import error though, I drop to a python shell and try to import the item. If it fails, then something is either wrong with the module (you'd be surprised how often I forget __init__.py), or it's not properly in your python path.
If the directory is called History, you should change import history
to import History
, as python imports are case-sensitive (on my Linux box, at least).
精彩评论