开发者

django standalone script import error

开发者 https://www.devze.com 2023-01-12 09:26 出处:网络
I have a working django site and I\'m trying to run a standalone script over its data. I am following this开发者_开发问答 article, but can\'t get it to work. I have tried two approaches:

I have a working django site and I'm trying to run a standalone script over its data. I am following this开发者_开发问答 article, but can't get it to work. I have tried two approaches:

1)

import sys, os
sys.path.append(os.path.abspath('..'))

os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'

from mysite.main.models import Image
#from main.models import Image #should work too

2)

import sys, os
sys.path.append(os.path.abspath('..'))

from django.core.management import setup_environ 
from mysite import settings
#import settings #should work too
setup_environ(settings)

from mysite.main.models import Image

Both gives me "AttributeError: 'module' object has no attribute 'models'" raised from the module I am trying to import (main.models).

The script itself is located in the project root of a working site, with the "main" app properly installed and working. There should be no problem with settings or models.


I struggled with a very similar error myself and this snippet from Django shell code (shell.py) did it for me:

from django.db.models.loading import get_models
loaded_models = get_models()

Put it before your model class import.


I don't see any reason why your import statement should not work. Make sure that the module structure matches the import command. The module path should be mysite -> main -> models. Some developers add an extra apps module in a project such that the path becomes mysite -> apps -> main -> models. Ensure that this is not the case for you.

To check, do the following from the Django shell as well as the Python REPL.

from mysite.main.models import Image

If this doesn't work you'll need to troubleshoot your module structure.


Just clone your manage.py file. Drop the last two lines line and append your code to the end. Works like a charm! For example mine now contains the following, which outputs data from one of my database items,

#!/usr/bin/env python
import os
import sys

if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "conf.settings_dev")
  #from django.core.management import execute_from_command_line
  #execute_from_command_line(sys.argv)
  from events.models import Event
  e = Event.objects.get(id="testID")
  print e.eventTitle

I suspect there might be a more official (and convoluted) way to do things but this is a good place to start in the meantime.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号