Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
344 views
in Technique[技术] by (71.8m points)

python - Django脚本,无需使用manage.py shell即可访问模型对象(Django script to access model objects without using manage.py shell)

I'm writing a script to import some model objects into the database my django application uses.

(我正在编写一个脚本,将一些模型对象导入到我的django应用程序使用的数据库中。)

In the past I've solved this by running ./manage.py shell and then import myscript .

(过去,我已经通过运行./manage.py shellimport myscript解决了这一问题。)

I'm sure there's a better way.

(我敢肯定有更好的方法。)

I'd like to be able to call a script from anywhere on my HD using python scriptname.py , and in the first few lines of that script it would do whatever imports / other operations necessary so that it can access model objects and behave as though it was run using manage.py shell .

(我希望能够使用python scriptname.py从HD的任何位置调用脚本,并且在该脚本的前几行中,它将执行任何必需的导入/其他操作,以便它可以访问模型对象并表现为尽管它是使用manage.py shell运行的。)

What do I need to add to my script to achieve this?

(要实现此目的,我需要添加什么内容?)

EDIT:

(编辑:)

Based on @Melug's answer, with addition of dynamically setting Python path to address the 'anywhere on my HD' part of the question:

(基于@Melug的答案,此外还动态设置了Python路径以解决问题的“ HD上的任何地方”:)

import sys
sys.path.append('c:\my_projec_src_folder')
from myproject import settings
from django.core.management import setup_environ
setup_environ(settings)
  ask by Trindaz translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Since Django 1.4 you should avoid using setup_environ(settings) (post by Melug) because it is deprecated.

(从Django 1.4开始,您应该避免使用setup_environ(settings) (由Melug发表),因为它已被弃用。)

Use the following instead and you will be able to access your model

(请改用以下内容,您将可以访问模型)

import os

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "your_project_name.settings")

# your imports, e.g. Django models
from your_project_name.models import Location

# From now onwards start your script..

Here is an example to access and modify your model:

(这是访问和修改模型的示例:)

if __name__ == '__main__':    
    # e.g. add a new location
    l = Location()
    l.name = 'Berlin'
    l.save()

    # this is an example to access your model
    locations = Location.objects.all()
    print locations

    # e.g. delete the location
    berlin = Location.objects.filter(name='Berlin')
    print berlin
    berlin.delete()

Example model:

(示例模型:)

class Location(models.Model):
    name = models.CharField(max_length=100)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...