python - 用于访问模型对象的 Django 脚本
问题描述
我的 django 项目叫 mybooks,应用是列表。我正在编写一个名为 searchBooks.py 的 python 脚本,它需要列表应用程序中的一些模型。searchBooks.py 脚本位于列表文件夹中(与 models.py 相同)但是,我无法访问模型。
我做了其他一些用户在这里提出的建议,包括
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mybooks.settings")
from listings.models import books
但是,我得到 ModuleNotFoundError: No module named 'listings'
我应该更改 settings.py 中的任何内容吗?或者可能是 searchBooks.py 的目录?
解决方案
您需要编写一个在 Django 上下文中运行的脚本,通过manage.py
. 这很容易。
在您的应用程序中,首先创建app/management/commands/__init__.py
(空文件,您可能需要创建文件夹)。然后,首先将此模板复制到app/management/commands/noop.py
:
# invoke with ./manage.py noop [--total] 1 2 3 ...
# script in app/management/noop.py with __init__.py
from django.core.management.base import BaseCommand
class Command( BaseCommand):
def add_arguments( self, parser): # parser is Python argparse parser
parser.add_argument( 'number_list', nargs='+', type=int,
help='any number of integers to add up',
)
parser.add_argument( '--total', action='store_true', default=False,
help='Print the total as well as the args'
)
parser.add_argument( '--file', type=self.infile)
def handle( self, *args, **options ):
# print( f'Args: {args}' ) # what are args?
if options['verbosity'] >= 2: # inherit default options, including verbosity and help.
# use --help to explore the others
print( f'Options: {options}' )
if options['total']:
total = sum( options['number_list'])
print( f'Total: {total}' )
if options['file']:
print('First line is:')
print( options['file'].readline() )
def infile( self, arg):
return open( arg, 'r')
如果您不熟悉 argparse,请查阅其文档(它是标准 Python,而不是 Django):https ://docs.python.org/3/library/argparse.html
一旦你确定它有效,你可以得到六个
./manage.py noop --total 1 2 3
将其作为起点复制到同一文件夹中的某个其他名称,然后对其进行修改以执行您希望从命令行执行的任何操作。您将首先添加
from listings.models import Whatever, ...
然后根据您定义的任何选项的指示,修改句柄方法以对它们做任何您想做的事情。
Django 文档:https ://docs.djangoproject.com/en/2.1/howto/custom-management-commands/
推荐阅读
- javascript - 如何编写新文档的 ID [firebase.firestore().onSnapshot()]
- xslt - xsl如何使用xsl删除父级下的大量xml元素
- go - golang是如何实现[]byte和string之间的转换的?
- javascript - 必须在页面上加载图像时,机车滚动无法与 Vue.js 一起使用
- java - Vertx 服务代理编译错误无法解析为类型
- amazon-web-services - SES 不向自己的已验证地址发送电子邮件,甚至测试电子邮件选项
- javascript - 单击时无法使导航栏折叠
- sql - JPA本机sql查询中的like子句
- sql - 无顺序保证的有条件的 LEAD/LAG
- sql - 如果组中至少有一条记录满足特定条件,如何编写查询以排除记录组?